PHP file_get_content在远程通信之前的准备,服务器中json_decode解析详解
来源:互联网 发布:淘宝不能搜网盘 编辑:程序博客网 时间:2024/05/29 04:42
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); //进行跨域访问 $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调用对象:101echo "解析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>";?>
1 0
- PHP file_get_content在远程通信之前的准备,服务器中json_decode解析详解
- json_decode在php中的一些无法解析的字符串
- 在php中json_encode与json_decode的使用方法
- 在PHP代码中处理JSON 格式的字符串【或用file_get_content得到的数据】
- php json_decode 解析中文
- php中curl、fsocket、file_get_content三个函数的使用比较
- php中curl、fsocket、file_get_content三个函数的使用比较
- PHP中json_decode的整型溢出问题
- php中json_decode()和json_encode()的使用方法
- php中json_decode()和json_encode()的使用方法
- PHP中json_decode的整型溢出问题
- php中json_decode()和json_encode()的使用方法
- php中json_decode()和json_encode()的使用方法
- php中json_decode()和json_encode()的使用方法
- php中json_decode()和json_encode()的使用方法
- php中json_decode()和json_encode()的使用方法
- php中json_decode()和json_encode()的使用方法
- php中json_decode()和json_encode()的使用方法
- static大显身手
- stl各种类型大致分析
- 博弈论(一):Nim游戏
- servlet实现文件下载
- Java的设计模式——单例
- PHP file_get_content在远程通信之前的准备,服务器中json_decode解析详解
- HDU 5701 中位数计数
- 企业大数据平台二:企业大数据平台环境准备
- 博弈论(二):Sprague-Grundy函数
- onmouseover 鼠标移入
- Android-下拉刷新库
- 企业大数据平台三:企业大数据平台安装
- 正确理解ThreadLocal
- ubuntu14.04LTS 安装后几个基本设置