I have a text file with a number of JSON records in it. Is there a simple way, using PHP to decode the records. Example:
{
'id':1
}
{
'id':2
}
I have a text file with a number of JSON records in it. Is there a simple way, using PHP to decode the records. Example:
{
'id':1
}
{
'id':2
}
If there is only one empty line between each JSON block of data, then next code would work, it process each line of file, if empty line is read, one block of JSON data has finished and it is displayed, then continues with the rest :
<?php
$arr = file( "data.json" ); // READ WHOLE FILE AS ARRAY OF STRINGS.
$block = ""; // STORE ONE "BLOCK" OF JSON DATA.
foreach ( $arr as $line ) // PROCESS EACH LINE IN FILE.
{ if ( strlen( $line ) > 2 ) // IF LINE CONTAINS MORE THAN LINEBREAK.
$block .= $line; // STORE LINE.
else { // EMPTY LINE FOUND (LINE WITH LINEBREAK ONLY, 0D,OA).
$json = json_decode( $block );
print_r( $json );
echo "<br/><br/>";
$block = ""; // CLEAR BUFFER FOR NEXT BLOCK OF JSON DATA.
}
}
// PRINT LAST BLOCK OF JSON DATA.
$json = json_decode( $block );
print_r( $json );
?>
Tested with this file :
{
"id":1
}
{
"id":2
}
{
"id":3
}