2013-03-11 56 views
1
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 
     } 

打开浏览器时,有一个Warning: Invalid argument supplied for foreach()。我不明白为什么我的论点是无效的。json_decode到数组?

如果我添加了if,没有任何反应,它显示了实际问题。但问题是什么是正确的方法来做到这一点?我很确定这很简单,但我一直在为此挣扎超过一个小时。我的JSON文件有这样的领域,所以我不认为会有问题:

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

请帮助我,我真的累了吧,我不知道该怎么办。所以... 我怎样才能解码文件到一个数组?

+1

你试过了吗,json_decode('data.json',true)? (真正的标志是数组输出,而不是对象) – jlasarte 2013-03-11 16:26:35

+0

foreach()在对象上和数组一样好 - 如果他得到一个'无效参数提供...'错误,那么他会传递其他东西(可能boolean false)。 – 2013-03-11 16:31:26

+0

是的,我已经试过真正的国旗编辑 – 2013-03-11 16:36:23

回答

2

您需要testson.json文件的内容不只是名称!

通过PHP收到内容:

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

确保没有被通过

var_dump(json_decode($json_string)); 

,然后测试它在文件中有效的JSON内容调用

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

更新: 当您保存文件并在几毫秒后访问它时,可能是因为文件系统太慢而没有向您显示正确的内容。

添加

fclose($fileout); 
clearstatcache(); 

file_get_contents();调用之前!

我建议使用file_put_contents()file_read_contents()得到 摆脱这样的问题!

+0

'的情况下工作非常感谢!但不会是更好的方法是使用'json_decode($ json_string,true)',以防万一? – 2013-03-11 16:39:15

+0

@BujancaMihai,它会更清晰。但是,由于PHP试图将变量类型转换为必要的变量类型,并使用额外的参数'真'! – powtac 2013-03-11 16:40:49

+0

仍然无法正常工作,我只是把它放在我的代码中:( – 2013-03-11 16:42:38

1

json_decode期待一个字符串,因为它是第一个参数。你传递的是我猜测的是一个文件名。你应该像这样首先加载文件...

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