您的位置:首页 > 编程语言 > PHP开发

PHP file_get_content在远程通信之前的准备,服务器中json_decode解析详解

2016-07-23 21:16 686 查看
file_get_content在远程通信之前:

1.需要给数据生成请求字符串,

2.转化为二进制流,

3.进行file_get_content远程访问。

4.再返回的数据中,在本地服务器可以用json_decode进行解析。

代码实现,以及对json_decode()函数解析的详解:

<?php
/**
* Created by PhpStorm.
* User: 洋   汪
* Date: 2016/7/20
* Time: 20:00
*/
header("Content-type:text/html;charset=utf-8");
function postTrans($url, $data)
{
//发送到服务器之前应该如何对数据进行编码
//POST的4中编码格式:
//1.(默认)application/x-www-form-urlencoded
//2.multipart/form-data(上传文件时候)
// 3.application/json
// 4.text/xml

//http_build_query()生成URL-encode之后的请求字符串。
$content = http_build_query($data);
$requestPost = array(
"http" => array(
"header" => "Content-Type:application/x-www-form-urlencoded\r\n" .
"Content-Length:" . strlen($content) . "\r\n" .
"User-Agent:MyAgent/1.0\r\n",
"method" => "POST",
"content" => $content
)
);

//转化为计算机的二进制流
$context = stream_context_create($requestPost);

4000
//进行跨域访问
$result = file_get_contents($url, false, $context, -1, 40000);
return $result;
}

//调用远程函数并传入远程ip服务器和数据,进行远程访问。
$result = postTrans("http://192.168.4.101:90/PHPStudy4/server.php", array("username" => "admin", "password" => "admin"));
//不解析的情况下。输出:未用解析时直接输出:{"code":"101","pass":"111"}
echo "未用解析时直接输出:" . $result . "<br>";
//不解析里边的数值是拿不出来的。输出:未用解析时['code']:{
echo "未用解析时['code']:" . $result["code"] . "<br>";

//接下来讲解,并用json_decode进行解析。
//当传过来的值为json_encode()方式传递时,php中用json_decode()解析。
//json_decode(接收到的数据,true/false(false为默认的))
//false情况:把接收的数据解析成对象;
//true情况:把传递的值,解析为数组。

//false情况的直接输出造成fatal error:Object of class stdClass could not be converted to string
//类stdClass的对象不能转换为字符串
//echo "解析false情况:" . json_decode($result) . "<br>";

//false情况以对象调用。输出:解析false情况->code调用对象:101
echo "解析false情况->code调用对象:" . json_decode($result)->code . "<br>";

//true情况以数组调用:
//true情况直接输出,输出Array这个词
echo "解析true情况调用对象:" . json_decode($result, true) . "<br>";
//数组形式调用。输出:解析true情况['']数组调用:101
$r = json_decode($result, true);
echo "解析true情况['']数组调用:" . $r["code"] . "<br>";
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息