我可以使用cURL搜索谷歌,但是ajax返回null

时间:2016-12-27 09:31:52

标签: php ajax curl

我无法return $data当我echo $data页面加载时(请参阅箭头---> getPage.php )。

但我希望将$data返回 page1.php 我会{"html":null,"url":"floret media"}您可以看到"html":null为什么会发生这种情况?当我在return $data中将echo $data替换为response tab时,我看到了这一点(使用整页)

> HTTP/1.1 200 OK Date: Tue, 27 Dec 2016 09:24:01 GMT Expires: -1
> Cache-Control: private, max-age=0 Content-Type: text/html;
> charset=ISO-8859-1 P3P: CP="This is not a P3P policy! See
> https://www.google.com/support/accounts/answer/151657?hl=en for more
> info." Server: gws X-XSS-Protection: 1; mode=block X-Frame-Options:
> SAMEORIGIN Set-Cookie:
> NID=93=XFlY_DE0XhLLdLDiTeHZi44J_z61nRxwTBInVkZlRVA3MsnuhB3iAqcR12lMs44dRI3dMWriif3USxysmiXDqm317uTYg08TzgYzFZa-VVgII_KE5fVsxueZcAmzlMCrOCw1LCSPCuIKfVI;
> expires=Wed, 28-Jun-2017 09:24:01 GMT; path=/; domain=.google.com;
> HttpOnly Accept-Ranges: none Vary: Accept-Encoding Transfer-Encoding:
> chunked

<!doctype html><html itemscope="" ><!--WHOLE PAGE --></html>
  

浏览器是否允许返回对调用ajax的响应?

page1.php中

var url = 'floret media';
$.ajax({
         url:"getPage.php",
         type:"POST",
         dataType:"json",
         data:{url:url},
        success: function(data){
                 console.log(data);

                 }
    });

getPage.php

    function curl_google($keyword){ 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, 
    'http://www.google.com/search?hl=en&q='.urlencode($keyword).'&btnG=Google+Search&meta='); 
    curl_setopt($ch, CURLOPT_HEADER, 1); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_FILETIME, true);  
    $data = curl_exec($ch); 
    //ob_flush();//Flush the data here
    if ($data === FALSE) {

        echo "cURL Error: " . curl_error($ch);

    }
    curl_close($ch); 

  ------>  return $data;  <---- // when i change it to echo $data it will work, but return $data; will not work i will get json response as {"html":null,"url":"floret media"}
    } 


$url = $_POST["url"];

$html = curl_google($url);


$response = json_encode(array("html"=>$html,"url"=>$url));

echo $response;

1 个答案:

答案 0 :(得分:1)

使用utf8_encode对html响应进行编码。替换以下声明

$response = json_encode(array("html"=>$html,"url"=>$url));

$response = json_encode(array("html" => utf8_encode($html), "url" => $url));

由于Google返回的响应中包含一些非utf8字符,因此在执行json_encode时会返回null。