Using the API with PHP

PHP has a powerful JSON parsing mechanism, which, because PHP is a dynamic language, enables PHP developers to program against a JSON object graph in a very straightforward way. Example 9 shows a PHP page that sends a request to the JSON interface using the file_get_contents API to call the JSON endpoint, and the json_decode function to turn the results into an object graph that can be walked and turned into HTML.

Example 9: Using the API with PHP

<html>
<head>
   <link href="styles.css" rel="stylesheet" type="text/css" />
 <title>PHP Bing</title>
</head>
<body><form method="post" action="<?php echo $PHP_SELF;?>"> 
 Type in a search:<input type="text" id="searchText" name="searchText" value="<?php 
 if (isset($_POST['searchText'])){
  echo($_POST['searchText']); }
  else { echo('sushi');}
  ?>"/>
        <input type="submit" value="Search!" name="submit" id="searchButton" />
<?php
if (isset($_POST['submit'])) {
$request = 'http://api.search.live.net/json.aspx?Appid=<YourAppIDHere>&sources=image&query=' . urlencode( $_POST["searchText"]);
$response  = file_get_contents($request);
$jsonobj  = json_decode($response);
echo('<ul ID="resultList">');                    
                
foreach($jsonobj->SearchResponse->Image->Results as $value)
{
echo('<li class="resultlistitem"><a href="' . $value->Url . '">');
echo('<img src="' . $value->Thumbnail->Url. '"></li>');

}
echo("</ul>");
} ?>
</form>
</body>
</html>