【问题标题】:Retrieve Json Data Using CURL PHP使用 CURL PHP 检索 Json 数据
【发布时间】:2019-05-21 10:27:29
【问题描述】:

在这里我们使用 CURL 检索数据并打印,然后保存到文件,然后将其插入数据库。

$curl = curl_init();
$options=array(
    CURLOPT_URL=>"http://api.abc.com/v1/products/search.json?q=ball",
    CURLOPT_RETURNTRANSFER =>true,
    CURLOPT_ENCODING =>"",
    CURLOPT_FOLLOWLOCATION =>true,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT=>30,
    CURLOPT_HTTP_VERSION=>CURL_HTTP_VERSION_1_0,
    CURLOPT_CUSTOMREQUEST => "GET", 
    CURLOPT_POSTFIELDS=>"", 
    CURLOPT_HTTPHEADER=> array(
        "authorization: AsiMemberAuth client_id=50041351&client_secret=55700485cc39f1",
        "cache-control: no-cache"
    ),
    CURLOPT_HEADER=> true
);


curl_setopt_array($curl, $options);
$response = curl_exec($curl);

$err = curl_error($curl);
curl_close($curl);

if ($err){
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

结果 json 很好。现在我想将它保存在 json 文件中?

【问题讨论】:

  • 您可以删除CURLOPT_CUSTOMREQUEST => "GET",CURLOPT_POSTFIELDS=>"", ,因为它们是多余的并且相互矛盾。
  • 好的,我会这样做的。谢谢大佬!!

标签: php json get


【解决方案1】:

要将字符串保存到 php 中的文件,可以使用 file_put_contents()

file_put_contents doc

file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int

您可以按如下方式更新您的代码:

if ($err){
    echo "cURL Error #:" . $err;
} else {
    echo $response;

    //Write response to file
    file_put_contents("my_file.json", $response)
}

【讨论】:

  • 感谢您的建议!完成了。
猜你喜欢
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 2015-10-05
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多