php获取远程json,php远程读取json的方法分析php

/ / 2024-11-19   阅读:2522
php获取远程json,php远程读取json的方法分析...

发送json格式的数据有直接使用get url的方式或者post过来的方式,下文我们为各位总结这两种方式的json数据读取方法。


1.直接以文件形式输出的方式:

header("Content-type:text/html;charset=utf-8");
function GetCurl($url){
$curl = curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_URL, $url);
curl_setopt($curl,CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$resp = curl_exec($curl);
curl_close($curl);
return $resp;
}
$resp = GetCurl("http://www.jquerycn.cn"); //这个是json数据文件
$resp = json_decode($resp,true);
header('Content-type: application/json');
echo json_encode($resp);

0896b037885ebe41ed597a6d2c105148.jpg


2. post过来的数据接受方式:

$json_string = $_POST["txt_json"];
if(ini_get("magic_quotes_gpc")=="1")
{
$json_string=stripslashes($json_string);
}
$user = json_decode($json_string);
echo var_dump($user);
?>

在这个文件中,首先得到html文件中POST表单域txt_json的值,放入变量$json_string中,而后判断,如果当前PHP的设定为magic_quotes_gpc=On,即传入的双引号等会被转义,这样json_decode函数无法解析,因此我们要将其反转义化。而后,使用json_decode函数将JSON文本转换为对象,保存在$user变量中,最终用echo var_dump($user);,将该对象dump输出出来


php的HTTP_RAW_POST_DATA


用Content-Type=text/xml 类型,提交一个xml文档内容给了php server,要怎么获得这个POST数据。


The RAW / uninterpreted HTTP POST information can be accessed with: $GLOBALS['HTTP_RAW_POST_DATA'] This is useful in cases where the post Content-Type is not something PHP understands (such as text/xml).


由于PHP默认只识别application/x-www.form-urlencoded标准的数据类型,因此,对型如text/xml的内容无法解析为$_POST数组,故保留原型,交给$GLOBALS['HTTP_RAW_POST_DATA'] 来接收。


另外还有一项 php://input 也可以实现此这个功能


php://input 允许读取 POST 的原始数据。和 $HTTP_RAW_POST_DATA 比起来,它给内存带来的压力较小,并且不需要任何特殊的 php.ini 设置。php://input 不能用于 enctype="multipart/form-data"。


应用:

a.htm
post.php
echo file_get_contents("php://input");?>

我要评论

昵称:
验证码:

最新评论

共0条 共0页 10条/页 首页 上一页 下一页 尾页
意见反馈