使用Bing搜索时URL编码失败

时间:2016-04-03 18:20:52

标签: php ajax url bing

我在这里有一个问题,我尝试将变量传输到我的PHP脚本,以便从Bing Search API中检索数据。

我使用以下AJAX代码:

var bingquery = 'bingquery=' + $('#query').val();
    console.log(bingquery);

    $.ajax({
        method: "POST",
        url: "hw8.php",
        dataType: "json",
        data: bingquery,
        success: function(jsondata){
            console.log('***Test for News Feeds***');
            console.log(jsondata); 
        }
        });

我的PHP是:

if (isset($_POST["bingquery"])){
    // Replace this value with your account key
    $accountKey = '***myaccountkey***';

    $WebSearchURL = 'https://api.datamarket.azure.com/Bing/Search/v1/' + 'News?$format=json&Query=';

    $cred = sprintf('Authorization: Basic %s', base64_encode($accountKey . ":" . $accountKey) );

    $context = stream_context_create(array(
        'http' => array(
            'header'  => $cred
        )
    ));

    $request = $WebSearchURL . urlencode( '\'' . $_POST["bingquery"] . '\'');

//if I hard code the request URL here, it does work.

      $response = file_get_contents($request, 0, $context);

      echo $response;

    } 

我想知道我的网址编码是否有问题?因为控制台说file_get_contents(0%27MYSYMBOL%27)失败,所以MYSYMBOL是我想要搜索的字符串。

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

根本没有关于编码的错误,urlencode应该使输入字符串url安全,这正是它正在做的事情,\在网址中具有特殊含义,因此它由函数编码。

<强>更新

你正在添加两个字符串,在PHP中.用于连接两个字符串,进行以下更改,

$WebSearchURL = 'https://api.datamarket.azure.com/Bing/Search/v1/News'; 

$request = $WebSearchURL .'?Query='.urlencode($_POST["bingquery"]).'&$format=json;