2

在这里使用 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 文件中?

4

1 回答 1

1

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

file_put_contents 文档

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)
}
于 2019-05-21T10:33:40.623 回答