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

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)
{
    //发送到服务器之前应该如何对数据进行编码
    //POST4中编码格式:
    //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 errorObject 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>";
?>



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值