PHP 中 API 调用返回的 JSON 中未定义索引

Undefined Index in JSON returned by an API call in PHP

提问人:Hacker 提问时间:1/25/2017 最后编辑:Ruslan OsmanovHacker 更新时间:4/10/2017 访问量:599

问:

这是我执行HTTP请求的PHP文件:

    $token='Food2forkKey';  //food2fork
    foo2fork  private key
    $fooddetail=new Food($token,"json");

$pid=$_GET['first'];
//$search='https://community-food2fork.p.mashape.com/search?key='.$token.'&q='.$pid;   //Food2fork
$search='http://food2fork.com/api/search?key='.$token.'&q='.$pid;
//key
echo $search;
$json=$fooddetail->call_url($search);
//echo $details;
if(!$json){
echo 'Error: Could not retrieve products list.';
exit();
}
//var_dump(json_decode($json,TRUE));
$details=json_decode($json,TRUE);
//var_dump($details);
echo $details;  

$title = $details['title'];
//print_r $title;
$publisher =  $details['publisher'];
//print_r $publisher;
$image=$details['source_url'];
//print_r $image;
?>
<html>
<head>

</head>
<body>
    <table border="1">
        <tr>
            <td><?php print_r ($title); ?></td>
            <td><img src="<?php print_r($image); ?>"</td>
        </tr>
    </table>    
</body>
</html>

This is Html file 


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

</head>

<body>
<form  method="get" action="foodsearch.php">
<input type="text" name="Search" />
<input type="submit" value="Submit" id="sub" />
</form>

</body>
</html>

脚本失败,并显示“undefine index”错误消息。这背后的原因是什么?

我使用 food2fork API。返回的 JSON 具有 和 键,但是当我尝试显示值时,脚本会记录上述错误消息。titlepublisher

php json api 未定义索引

评论

0赞 Niklesh Raut 1/25/2017
分享价值,为什么在img src中如此?$jsonprint_r($image);
0赞 mith 1/25/2017
你能显示 print_r($details) 值吗?
0赞 Ruslan Osmanov 1/25/2017
在使用之前,您应该检查密钥是否确实存在,例如:if (isset($details['publisher'])) { ... }
0赞 Hacker 1/25/2017
用户搜索时,我只想要五个产品显示

答: 暂无答案