-1

I am trying to return data through JSON and save it to a TXT file

The issue I am facing is that with each iteration in the $array_1 the data is returned all in one line

I want to return the data in a line with each iteration and not to have all data in one line for the iteration done.

<?php
$array_1 = array(4901,2507,2644);
$array_length = count($array_1);
$iterator=0;
while($iterator < $array_length)
{

$record_id = $array_1[$iterator];
$url = "https://example.com" . $record_id;
$curl = curl($url);
$json = fetch_value($curl, '<script type="application/ld+json">', '</script>');
$movie_id = fetch_value($curl, 'id="page_id" value="', '">');
$name = fetch_value($curl, '"name":"', '",');

 $movie_info[] = array(
                "0" => $movie_id,
                "1" => $name,
);
   
$iterator++;
}

$result = array("result" => $movie_info);
$data = json_encode($result, JSON_UNESCAPED_UNICODE);

$data = PHP_EOL . $data;
$myfile = file_put_contents('final.txt', $data.PHP_EOL , FILE_APPEND | LOCK_EX);
?>

The way it is returned now Final.txt result:

{"result":[["4901","movie #1",],["2507","movie #2"],["2644","movie #3"]]}

I want to return the data in Final.txt:

{"result":[["4901","movie #1",],
["2507","movie #2"],
["2644","movie #3"]]}
  • 1
    You can add the flag `JSON_PRETTY_PRINT` to get the data more formatted and readable. It won't look exactly like you ask, it will be more readable. If you want the exact format you posted, you will need to write a script that formats it yourself, but I don't see why it would matter, tbh? – M. Eriksson May 23 '22 at 08:32
  • 1
    Btw, is that really the result you're getting? I don't see how you could get the trailing `,` in `["4901","movie #1",]` (which is invalid json) – M. Eriksson May 23 '22 at 08:38

0 Answers0