2016-04-03 33 views
1

我在這裏有一個問題,我嘗試將一個變量傳輸到我的PHP腳本以從Bing搜索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; 

    } 

我不知道是否有什麼毛病我的URL編碼?由於控制檯說file_get_contents(0%27MYSYMBOL%27)失敗,MYSYMBOL是我想要搜索的字符串。

非常感謝您的幫助!

回答

1

編碼根本沒有錯,urlencode應該使輸入字符串url安全,這正是它在做什麼,\在url中有特殊含義,因此它正在被函數編碼。

UPDATE

你加入了兩個字符串,在PHP .是用來連接兩個字符串,做如下修改,

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

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

@保羅看到更新的答案,希望幫助。 – Vincent

+0

非常感謝!我應該用過。而不是+ ...不太熟悉PHP。 – Paul

+0

發生在我們身上,歡呼聲 – Vincent