如何在PHP中回显cURL结果?

时间:2014-11-13 13:27:17

标签: php json curl

这是一个网址→https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=snoopy&rsz=1

这是我的PHP代码

<?php
    $url = "https://ajax.googleapis.com/ajax/services/search/images?"."v=1.0&q=snoopy";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $body = curl_exec($ch);
    curl_close($ch);

    $json = json_decode($body);
?>

我想从结果中回显所有图片网址 (例如:http://img2.wikia.nocookie.net/__cb20110331075248/peanuts/images/6/62/Snoopy.gif

但我不知道如何回应它们 希望有人可以帮助我,谢谢!

2 个答案:

答案 0 :(得分:1)

为了回应确切的结果,只需使用:

echo $body; //echoes json string

如果您想回显确切的链接,请回显如下:

echo $json->responseData->results[0]->url; //echoes http://img2.wikia.nocookie.net/__cb20110331075248/peanuts/images/6/62/Snoopy.gif

或者你可以foreach()两次(或一次......)然后echo $res->url直接:)你的选择!

答案 1 :(得分:1)

也许是这样的:

<?php
    $url = "https://ajax.googleapis.com/ajax/services/search/images?" .
   "v=1.0&q=barack%20obama&userip=INSERT-USER-IP";

   // sendRequest
   // note how referer is set manually
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_REFERER, 'http://example.com');
   $body = curl_exec($ch);
   curl_close($ch);

   // now, process the JSON string
    $pics = json_decode($body);
    $ret='';
    if($pics){
       foreach($pics->responseData->results as $pic)
          $ret .= $pic->url.'<br>';
    }
    echo $ret;
?>