0

I'm trying to write a json file with data gathered via get requests. The json file is a 2D array of strings, but when the data is written to the file, the nested array is written twice.

<?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 before the script runs:

[]

What the script prints:

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 after the script:

[["128,54","128,54","128,54","30\/12"],["128,54","128,54","128,54","30\/12"]]

I tried opening the file like this: $fp = fopen("j.json", "r+"); and at the and i changed the script:

$s = "\"".json_encode($loaded)."\"";

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

And I found out that a null is being written too:

[]"[["128,54","128,54","128,54","30\/12"]]""null"

1 Answers1

1

The browser sends two requests when visiting a url, a request to the php file and another request to /favicon.ico. The second request is send to check if the site has a favicon. This second requests causes the script to execute twice.

The request for the favicon can be prevented by following the steps described here: https://stackoverflow.com/a/38917888/6310593

MaartenDev
  • 5,631
  • 5
  • 21
  • 33