如何从Bing Search API获取结果?

时间:2015-07-18 12:28:09

标签: php api search bing

所以,在我的上一个问题(Invalid argument supplied for foreach() - Bing Search API)中,我发现我没有得到结果的原因是因为“jsonObj-> d->结果不是数组!”

PHP脚本:

<script src='./menu_20150718.js'></script>

HTML:

<?php

$acctKey = 'key';

$rootUri = 'https://api.datamarket.azure.com/Bing/Search';

$contents = file_get_contents('bing_basic.html');

if ($_POST['query'])
{

$query = urlencode("'{$_POST['query']}'");

$serviceOp = $_POST['service_op'];

$requestUri = "$rootUri/$serviceOp?\$format=json&Query=$query";

$auth = base64_encode("$acctKey:$acctKey");

$data = array('http' => array('request_fulluri' => true,'ignore_errors' => true,'header' => "Authorization: Basic $auth"));

$context = stream_context_create($data);

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

$jsonObj = json_decode($response);
$resultStr = '';
foreach($jsonObj->d->results as $value)
{
    switch ($value->__metadata->type)
    {
        case 'WebResult':
        $resultStr .= "<a href=\"{$value->Url}\">{$value->Title}</a><p>{$value->Description}</p>";
        break;
        case 'ImageResult': $resultStr .= "<h4>{$value->Title} ({$value->Width}x{$value->Height}) " . "{$value->FileSize} bytes)</h4>" . "<a href=\"{$value->MediaUrl}\">" . "<img src=\"{$value->Thumbnail->MediaUrl}\"></a><br />";
        break;
    }
}

$contents = str_replace('{RESULTS}', $resultStr, $contents);

}

echo $contents;

?>

这应该很简单,只需复制并粘贴本文档中的代码即可使用:https://onedrive.live.com/view.aspx?resid=9C9479871FBFA822!112&app=Word&authkey=!ANNnJQREB0kDC04

我还必须提到我正在使用Bing Search API - 仅限Web结果,而不仅仅是Bing Search API,因此我不知道该文档是否只是关于Bing Search API

0 个答案:

没有答案