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()函数解析的详解:
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>"; ?>
相关文章推荐
- 使用 Python 处理 JSON 格式的数据
- XML 与 JSON 优劣对比
- VBA将excel数据表生成JSON文件
- C#实现子窗体与父窗体通信方法实例总结
- newtonsoft.json解析天气数据出错解决方法
- vbs 解析json jsonp的方法
- Ruby和Ruby on Rails中解析JSON格式数据的实例教程
- Extjs4如何处理后台json数据中日期和时间
- C#实现将类的内容写成JSON格式字符串的方法
- JQuery ajax返回JSON时的处理方式 (三种方式)
- jquery JSON的解析方式示例介绍
- c#版json数据解析示例分享
- ASP JSON类文件的使用方法
- java和c#使用hessian通信的方法
- C# JSON格式化转换辅助类 ConvertJson
- win32下进程间通信(共享内存)实例分析
- C#实现对Json字符串处理实例
- C#实现Json转Unicode的方法
- 深入理解PHP JSON数组与对象
- php解析json数据实例