php - fwrite() 两次写入一个 json 编码的数组
问题描述
我正在尝试使用通过获取请求收集的数据编写一个 json 文件。json文件是一个二维的字符串数组,但是当数据写入文件时,嵌套数组会被写入两次。
<?php
//used for parsing html
include("simple_html_dom.php");
//read the file
$fp = fopen("j.json", "r");
$t = fread($fp, filesize("j.json"));
fclose($fp);
$loaded = json_decode($t);
//print the loaded array
print_r($loaded);
//gathering the data
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo1 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
$data = file_get_html($url)->find("span[class=ora] b", 0)->plaintext;
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo2 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo3 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
//adding the new data to the array
array_push($loaded, array($prezzo1, $prezzo2, $prezzo3, $data));
//the new json string is parsed and ready to be written
$s = json_encode($loaded);
//printing stuff to ensure the data is correct
echo "<br>".$s.", type=".gettype($s)."<br>";
print_r($loaded);
//write the new json string to the same file
$fp = fopen("j.json", "w");
fwrite($fp, $s);
fclose($fp);
?>
j.json 在脚本运行之前:
[]
脚本打印的内容:
Array ( )
[["128,54","128,54","128,54","30\/12"]], type=string
Array ( [0] => Array ( [0] => 128,54 [1] => 128,54 [2] => 128,54 [3] => 30/12 ) )
脚本后的 j.json:
[["128,54","128,54","128,54","30\/12"],["128,54","128,54","128,54","30\/12"]]
我尝试像这样打开文件:$fp = fopen("j.json", "r+");
然后我更改了脚本:
$s = "\"".json_encode($loaded)."\"";
echo "<br>".$s.", type=".gettype($s)."<br>";
print_r($loaded);
fwrite($fp, $s);
fclose($fp);
我发现也写了一个空值:
[]"[["128,54","128,54","128,54","30\/12"]]""null"
解决方案
浏览器在访问 url 时发送两个请求,一个对 php 文件的请求,另一个对/favicon.ico
. 发送第二个请求以检查站点是否具有图标。这第二个请求导致脚本执行两次。
可以按照此处描述的步骤阻止对 favicon 的请求:https ://stackoverflow.com/a/38917888/6310593
推荐阅读
- node.js - AWS DynamoDB-Data-Mapper NodeJS
- c# - 如何拆分数组中的键/值对?
- php - 如何在 Mysql 数据库中插入 AM 和 PM?
- ionic-framework - 在节点模块中运行时出现离子错误
- php - 在 Vtiger 7.0 中添加新的 UI 类型
- c - 在 C-Linux 中使用制表符而不是 Enter 键获取输入
- python - Python:IndexError:列出超出范围的索引和类对象
- intellij-idea - intellij,当我的鼠标指向 IntelliJ SDK 中的右侧滚动时,源预览很慢
- jquery - AJAX:使浏览器显示“保存密码和用户名”
- sql-server - SQL Server ogr2ogr 批处理无法访问 ogr_MSSQLSpatial.dll