简体   繁体   中英

json_decode to an array?

foreach ($likes as $like) {
    // Extract the pieces of info we need from the requests above
    $id = idx($like, 'id');
    $item = idx($like, 'name');

    fwrite($fileout,json_encode($like));
    fwrite($fileout,PHP_EOL );
}

$json_string = file_get_contents('testson.json');
$get_json_values=json_decode($json_string,true);

foreach ($get_json_values as $getlikes) {  ?>
          <li>
            <a href="https://www.facebook.com/<?php echo $getlikes['id']; ?>" target="_top">
          </li>
        <?php
      } 

When opening the browser, there is a Warning: Invalid argument supplied for foreach() . I don't understand why would my arguments be invalid.

If I add the if, nothing happens, which shows what the actual problem is. But the question is WHAT IS THE PROPER WAY TO DO THIS ? I'm pretty sure it's very simple, but i've been struggling with this for more than an hour. My json files has fields like this, so I don't think there would be the problem:

{"category":"Musician\/band","name":"Yann Tiersen (official)","id":"18359161762"}

Please help me, I really got tired with it, and I don't know what to do. So... how can I decode the file into an array?

You need the contents of the testson.json file not just the name!

Receive the contents via PHP:

$json_string = file_get_contents('testson.json');

Make sure there are valid JSON contents in the file by testing it via

var_dump(json_decode($json_string));

And then call

foreach (json_decode($json_string) as $getlikes) {  ?>

Update: When you save the file and access it miliseconds later it might be that the filesystem is too slow and not showing you the correct content.

Add

fclose($fileout);
clearstatcache();

before the file_get_contents(); call!

I recommend to use file_put_contents() and file_read_contents() to get rid of such problems!

json_decode is expecting a string as it's first parameter. You are passing what I'm guessing is a filename. You should load the file first like so...

$json = file_get_contents('testson.json');
$data = json_decode($json);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM