【问题标题】:Parsing JSON results with PHP使用 PHP 解析 JSON 结果
【发布时间】:2013-07-06 21:25:55
【问题描述】:

我正在尝试构建一个元搜索引擎,并使用以下代码生成 JSON 结果。

<?php

$search = $_GET['results'];
if(isset($_GET['results']) && $_GET['results'] != "")
{

    echo "<br />Your Search Result Array:<br /><br />";

$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
    . "q=".str_replace(' ', '%20', $_GET['results']);

$ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com');
$body = curl_exec($ch);
curl_close($ch);


$json = json_decode($body);

print_r($json);

这给了我 JSON 未排序的结果,没有顺序或超链接。我正在尝试使用 PHP 解析结果。当我在搜索引擎中输入“你好”时,它给了我

stdClass Object ( [responseData] => stdClass Object ( [results] => Array ( [0] =>stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.hellomagazine.com/ [url] => http://www.hellomagazine.com/ [visibleUrl] => www.hellomagazine.com [cacheUrl] => http://www.google.com/search?q=cache:QzMhUCC4zBoJ:www.hellomagazine.com [title] => HELLO! Online: celebrity & royal news, magazine, babies, 

作为前 4 行。我试过了

foreach($results['responsedata']['results']['GsearchResultsClass'] as $result)
{

echo $result['title'].'<br/>';
}   

但它在 foreach 行上给我留下了很多错误。

非常感谢任何建议,我不熟悉 JSON,所以欢迎任何关于如何解析结果的帮助。

【问题讨论】:

  • 因为$results 不是一个数组。 var_dump($results); 看看。还要检查json_decode()的第二个参数
  • 如果你想以数组的形式访问它,请将json_decode这一行更改为:$json = json_decode($body, true);
  • 提供你完整的 json key=>value 输出。请使用$json = json_decode($json, true); 获得正确的输出。
  • 旁注,当你从不使用$search 并且总是将其称为$_GET['results'] 时,为什么要分配$search = $_GET['results'];?

标签: php javascript json search-engine


【解决方案1】:

您使用默认返回类型json_encode,它返回一个stdClass 对象。如果您想将其作为关联数组使用,请将以下参数传递给 json_decode。

$json = json_decode($json, true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-15
    • 2017-05-31
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    相关资源
    最近更新 更多