繁体   English   中英

PHP API将JSON保存到文件,然后读取文件

[英]PHP API saving JSON to file, then reading the file

遇到麻烦了。

基本上,我正在尝试访问API以检索数据。 我仅限于一定数量的连接,因此我的计划是检索数据,将其保存到主机上的文本文件中,然后根据需要从该文件中进行读取。 然后,我将使用cron作业每隔几个小时用新数据重新填充文件。

无论如何,我已经登录了API并检索了数据,并且可以“实时”显示数据而没有问题。

当尝试保存数据并从文本文件读取数据时,问题就开始了。 这是一个多深度数组。

收货代码

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, 'URL GOES HERE');
//prepare the field values being posted to the service
$data = array("appkey" => "KEY","account" => "ACCOUNT" );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

//make the request
$result = curl_exec($ch);
curl_close($ch);

这样可以使代码正常运行,我可以显示

$properties = json_decode($result, true);
$properties = $properties['properties'];
//pr($parsed_json);

foreach($properties as $key => $value) {

    if ($_GET[section] == "sale") {

        if ($value['category_id'] == "1") {

            displayProp ($address, $value['price'], $value['qualifier_name'], $value['summary']); 

        }

    } elseif ($_GET[section] == "rent") {

        if ($value['category_id'] == "2") {

            displayProp ($address, $value['price'], $value['freq_name'], $value['summary']); 

        }
    }
}

这可行。

然后我尝试将json保存到一个文本文件中

file_put_contents('properties.txt', json_decode($result));

这样可以将数据保存在文件中。 但是,当尝试从中读取内容时,无论尝试如何,都会出现随机错误。 有人可以帮助您阅读文本文件并输出数组吗?

使用JSONLint我验证数据并得到以下错误

Parse error on line 1:
"{    \"status\": \
^
Expecting '{', '['

有任何想法吗?

json_decode保存并读取原始JSON。

json_decode()将返回一个数组或对象(通常来说)。 您不能只是将数组/对象写到文件中。 在字符串上下文中写一个数组只会给您文字Array

为什么不只写出原始JSON文本呢?

file_put_contents('cache.json', file_get_contents($url));

接着

$data = json_decode(file_get_contents('cache.json'));

每次都将花费一些cpu时间进行解码,但是至少您将获得真实数据,而不是损坏的Array或其他内容。

如果需要对结果进行json_decode并使用该结果,则需要对数据进行serialize和反unserialize

一种保存方式...

file_put_contents('properties.txt', serialize(json_decode($result)));

加载...

$result = unserialize(file_get_contents('properties.txt'));

这样可以确保每次运行都正确保留数据结构。 当存储为JSON时,除非指定,否则不清楚JSON对象是PHP对象还是关联数组。 serialize没有这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM