php - Invalid argument supplied for foreach() - Bing Search API -
this php code:
<?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 $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; ?>
and tis html:
<html> <head> <title>bing search tester (basic)</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> </head> <body> <h1>bing search tester (basic)</h1> <form method="post" action="bing_basic.php"> <label for="service_op">service operation</label><br/> <input name="service_op" type="radio" value="web" checked /> web <input name="service_op" type="radio" value="image" /> image <br/> <label for="query">query</label><br/> <input name="query" type="text" size="60" maxlength="60" value="" /><br /><br /> <input name="bt_search" type="submit" value="search" /> </form> <h2>results</h2> {results} </body> </html>
why keep getting error ? duplicate way, other questions didn't have code , there no answers question.
also, i'm not familiar php objects , json..
api documentation: https://onedrive.live.com/view.aspx?resid=9c9479871fbfa822!112&app=word&authkey=!annnjqreb0kdc04
double check ensure $jsonobj->d->results indeed array or not empty.
if( ( is_array( $jsonobj->d->results ) && ( ! empty( $jsonobj->d->results ) ) { foreach($jsonobj->d->results $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; } } } else { if( ! is_array( $jsonobj->d->results ) { echo "jsonobj->d->results not array!"; } elseif( empty( $jsonobj->d->results ) { echo "jsonobj->d->results empty!"; } }
Comments
Post a Comment