php json read file

EvilNabster

storage.json :

{"544aee0b0a00f":{"p_name":"testname","p_about":null,"file":"images\/1.png"}}
{"548afbeb42afe":{"p_name":"testname2","p_about":null,"file":"images\/2.png"}}
{"549afc8c8890f":{"p_name":"testname3","p_about":null,"file":"images\/3.jpg"}}

Now the numbers with letters at the beginning are uniqid() function that been called when writing items to the file.

<?php
$storage_file = 'storage.json';
$storage = file_get_contents($storage_file);
$storage = json_decode($storage,true);
$storage = empty($storage) ? array() : $storage;
print_r($storage)
?>

Now i have tried to display all records from the json file but it works ONLY if i have 1 record in file, if i have more than 1 , for like here about ( 3 records ) than the result i get is simple text: Array()

Could anybody help me out ? I'm kinda stuck over here, no idea what to do to fix the issue

meda

If you try to decode all at once it will fail due to invalid JSON because you need an array to hold multiple objects.

Instead you need to decode each line one by one:

<?php
$storage_file = 'storage.json';
$storage = file_get_contents($storage_file);
$lines = explode("\n", $storage);

for ($i=0;$i<count($lines);$i++)  
{
    $data = json_decode($lines[$i],true);
    print_r($data);
}

?>

<?php
$storage_file = 'storage.json';
$storage = file_get_contents($storage_file);
$lines = explode("\n", $storage);

foreach ($lines as $line)  
{
    $data = json_decode($line,true);
    print_r($data);
}

?>

<?php
$storage_file = 'storage.json';
$storage = file_get_contents($storage_file);
$lines = explode("\n", $storage);

foreach ($lines as $line)  
{
    $data = json_decode($line, true);
    foreach ($data as $key => $value) {
        echo "p_name = ".$data[$key]["p_name"]."\n";
    }
}

?>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related