【问题标题】:URL encoding failed when using Bing Search使用必应搜索时 URL 编码失败
【发布时间】:2016-04-03 18:20:52
【问题描述】:

我有一个问题,我尝试将一个变量传输到我的 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;

    } 

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

非常感谢您的帮助!

【问题讨论】:

    标签: php ajax url bing


    【解决方案1】:

    编码完全没有问题,urlencode 应该使输入字符串 url 安全,这正是它正在做的事情,\ 在 url 中具有特殊含义,因此它正在被编码按功能。

    更新

    你是把两个字符串相加,在PHP中.是用来连接两个字符串的,做如下修改,

    $WebSearchURL = 'https://api.datamarket.azure.com/Bing/Search/v1/News'; 
    
    $request = $WebSearchURL .'?Query='.urlencode($_POST["bingquery"]).'&$format=json;
    

    【讨论】:

    • 非常感谢!我应该使用 .而不是 +... 对 PHP 不太熟悉。
    猜你喜欢
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 2016-03-08
    相关资源
    最近更新 更多