我正在尝试将来自API连接的JSON响应放入JSON文件中,但是当我这样做时,我只在JSON文件中获得值true。
API PHP函数:
public function Get_Reviews(){
$token = 'CDF494791E05F36531FA0F5F';
$headers[] = 'Authorization: Bearer ' . $token;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => '[URL]',
CURLOPT_HTTPHEADER => $headers
));
$response = curl_exec($curl);
curl_close($curl);
return json_encode($response);
}
以及将响应放在JSON文件中的代码:
$api = new Reviews();
$reviews = $api->Get_Reviews();
$file = "reviews_created.json";
unlink($file);
$fp = fopen($file, 'w');
fwrite($fp, $reviews);
fclose($fp)
当我var_dump($ reviews)时,我得到一个干净的JSON响应,我可以手动将其复制到JSON文件中,但我需要使其动态化。
我希望有人能帮助我。
答案 0 :(得分:0)
检查此示例代码。它在我身边工作得很好。
<?php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "your API end point"
));
// Send the request & save response to $resp
$result = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
//header('Content-Type: application/json');
//echo $result;
$file = 'product.json';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= $result;
// Write the contents back to the file
file_put_contents($file, $current);
注意:将目标JSON文件作为写入权限。