【问题标题】:Put JSON content in a JSON file将 JSON 内容放入 JSON 文件中
【发布时间】:2017-03-01 02:50:34
【问题描述】:

我正在尝试将来自 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 文件中,但我需要使其动态化。

我希望任何人都可以帮助我。

【问题讨论】:

  • 你能不能用“echo”而不是 var_dump 来测试,看看你会得到什么?
  • 显示正确 json 的不是您的 var_dump(),而是您的 curl 调用。要捕获结果而不是显示结果,您需要将 CURLOPT_RETURNTRANSFER 设置为 true。

标签: php json file server


【解决方案1】:

检查此示例代码。它在我身边运行良好。

<?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 文件授予写入权限。

【讨论】:

  • CURLOPT_RETURNTRANSFER => 1 成功了,谢谢!
猜你喜欢
  • 2016-12-24
  • 1970-01-01
  • 2021-02-06
  • 2017-10-07
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多