遇到这个问题。
基本上,我正在尝试访问 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
没有这个问题。