我正在嘗試使用通過獲取請求收集的數(shù)據(jù)編寫一個 json 文件。json文件是一個二維的字符串?dāng)?shù)組,但是當(dāng)數(shù)據(jù)寫入文件時,嵌套數(shù)組會被寫入兩次。<?php//used for parsing htmlinclude("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 arrayprint_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 arrayarray_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 correctecho "<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 在腳本運行之前:[]腳本打印的內(nèi)容:Array ( )[["128,54","128,54","128,54","30\/12"]], type=stringArray ( [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);我發(fā)現(xiàn)也寫了一個空值:[]"[["128,54","128,54","128,54","30\/12"]]""null"
1 回答

SMILET
TA貢獻(xiàn)1796條經(jīng)驗 獲得超4個贊
瀏覽器在訪問 url 時發(fā)送兩個請求,一個對 php 文件的請求,另一個對/favicon.ico
. 發(fā)送第二個請求以檢查站點是否具有圖標(biāo)。這第二個請求導(dǎo)致腳本執(zhí)行兩次。
- 1 回答
- 0 關(guān)注
- 232 瀏覽
添加回答
舉報
0/150
提交
取消