0

I have a text file called test.txt with the following contents:

{"FirstName":"John","Title":"","Surname":"Smith"}
{"FirstName":"Daniel","Title":"","Surname":"Smith"}

I'd like to loop through this JSON in a PHP script so my output is ultimately:

John Smith
Daniel Smith

My current PHP code is:

$fn = fopen("./test.txt","r");
while(! feof($fn))  {
  $line = fgets($fn);
  // grab data from JSON
}
fclose($fn);

How would I grab each element & output it in my page?

John Conde
  • 217,595
  • 99
  • 455
  • 496
michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

1 Answers1

2

You would use json_decode() to get that data as an array or object (default).

JSON as an object:

$fn = fopen("./test.txt","r");
while(! feof($fn))  {
  $line = fgets($fn);
  $record = json_decode($line);
  echo $record->FirstName; // etc
}
fclose($fn);

JSON as an array:

$fn = fopen("./test.txt","r");
while(! feof($fn))  {
  $line = fgets($fn);
  $record = json_decode($line, true);
  echo $record['FirstName']; // etc
}
fclose($fn);

Demo

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • When I use the first one, my script just goes on an infinite loop and doesn't output anything. Same goes for 2nd script. Spinner just keeps loading in browser and never outputs. Any ideas why? – michaelmcgurk Apr 27 '19 at 19:33
  • 1
    Decoding the JSON won't do that. This basic code snippet won't either unless there is an issue with the file but I can't debug that from here. – John Conde Apr 27 '19 at 19:34
  • My bad. `test.txt` was called `test` without the `.txt` in my local test environment. All fixed now. Thanks so much :-) – michaelmcgurk Apr 27 '19 at 19:36