doucuo4413
2016-09-21 15:19
浏览 59
已采纳

使用PHP cURL获取JSON数据

I have a simple script that outputs some JSON. I'm trying to retrieve the JSON contents in a variable with another PHP script, but when I do a var_dump(), I'm getting NULL instead of the JSON data.

Here's the JSON. The only output is: {"ProductID":"1000096","ProductStyleID":"1001029","ProductCategoryID":"1000004"}

json.php

$arr['ProductID'] = "1000096";
$arr['ProductStyleID'] = "1001029";
$arr['ProductCategoryID'] = "1000004";

$json_arr = json_encode($arr);
echo $json_arr;

And here's the cURL script, which right now is outputting NULL:

curl.php

$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "/json.php");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec ($curl);
curl_close ($curl);
var_dump(json_decode($result, true));

How can I retrieve the JSON echoed in the json.php script?

图片转代码服务由CSDN问答提供 功能建议

我有一个输出一些JSON的简单脚本。 我正在尝试使用另一个PHP脚本检索变量中的JSON内容,但是当我执行var_dump()时,我得到的是NULL而不是JSON数据。

这是 JSON。 唯一的输出是: {“ProductID”:“1000096”,“ProductStyleID”:“1001029”,“ProductCategoryID”:“1000004”}

json。 php
  $ arr ['ProductID'] =“1000096”; 
 $ arr ['ProductStyleID'] =“1001029”; 
 $ arr ['ProductCategoryID']  =“1000004”; 
 
 $ json_arr = json_encode($ arr); 
echo $ json_arr; 
   
 
 

这是cURL脚本,现在是 输出NULL:

curl.php
  $ curl = curl_init(); 
curl_setopt($ curl,CURLOPT_URL,“/ json。  php“); 
curl_setopt($ curl,CURLOPT_RETURNTRANSFER,1); 
 
 $ result = curl_exec($ curl); 
curl_close($ curl); 
var_dump(json_decode($ result,true)); 
 <  / code>  
 
 

如何检索json.php脚本中回显的JSON?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • donglang2010 2016-09-21 15:32
    已采纳

    If you see a basic CURL example:- http://php.net/manual/en/curl.examples-basic.php

    You come to know that instead of:-

    "/json.php"

    You need to give full path like:-

    (http://...) or (https://...) for your file (based on your server)

    Note:- Rest of your code seems perfectly fine.Thanks

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dpvp56187 2016-09-21 15:34

    This is the URL to get the data:-

    $url="https://.../api.php?action";
    

    Using cURL:

    //  Initiate curl
    $cuh = curl_init();
    // Disable SSL verification
    curl_setopt($cuh, CURLOPT_SSL_VERIFYPEER, false);
    // Will return the response, if false it print the response
    curl_setopt($cuh, CURLOPT_RETURNTRANSFER, true);
    // Set the url
    curl_setopt($cuh, CURLOPT_URL,$url);
    // Execute
    $result=curl_exec($cuh);
    // Closing
    curl_close($cuh);
    
    // Will dump a beauty json :3
    var_dump(json_decode($result, true));
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题