一聚教程网:一个值得你收藏的教程网站

热门教程

php远程读取json的方法分析

时间:2022-06-24 17:09:19 编辑:袖梨 来源:一聚教程网

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.111com.net"); //这个是json数据文件
$resp = json_decode($resp,true);
header('Content-type: application/json');
echo json_encode($resp);

php远程读取json的方法分析

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


热门栏目