Php fwrite()将json编码的数组写入两次

Php fwrite()将json编码的数组写入两次,php,json,Php,Json,我正在尝试编写一个json文件,其中包含通过get请求收集的数据。json文件是一个字符串的2D数组,但当数据写入该文件时,嵌套数组会被写入两次 <?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_d

我正在尝试编写一个json文件,其中包含通过get请求收集的数据。json文件是一个字符串的2D数组,但当数据写入该文件时,嵌套数组会被写入两次

<?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);
?>
脚本打印的内容:

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"]]
$s = "\"".json_encode($loaded)."\"";

echo "<br>".$s.", type=".gettype($s)."<br>";
print_r($loaded);
fwrite($fp, $s);
fclose($fp);
我试着像这样打开文件:$fp=fopenj.json,r+;最后,我改变了剧本:

[["128,54","128,54","128,54","30\/12"],["128,54","128,54","128,54","30\/12"]]
$s = "\"".json_encode($loaded)."\"";

echo "<br>".$s.", type=".gettype($s)."<br>";
print_r($loaded);
fwrite($fp, $s);
fclose($fp);

浏览器在访问url时会发送两个请求,一个是对php文件的请求,另一个是对/favicon.ico的请求。发送第二个请求以检查站点是否有favicon。这第二个请求导致脚本执行两次


可以按照此处描述的步骤阻止favicon请求:

以下是解决问题的方法:太好了,将其添加到答案中!