This is a simple yet powerful way to get Bing’s Site Search API working on your site in PHP. Simply update the $config variables below and you’ll be good to go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
<?php define('TITLE', 'Search Results'); include('header.php'); $config['appid'] = "01234567890"; // change this $config['search_domains'] = array("domain1.com", "domain2.com"); $config['results_per_page'] = 20; $url = "http://$_SERVER[HTTP_HOST]$_SERVER[PHP_SELF]"; ?> <?php echo (isset($_REQUEST['q']) ? "<h1>Search Results</h1>" : "<h1>Search</h1>"); ?> <form method="get"> <div style="text-align:right"> <input type="text" id="q" name="q" value="<?php echo (isset($_REQUEST['q']) ? $_REQUEST['q'] : 'Search...'); ?>"/> <input type="submit" value="Search" name="submit" id="searchButton" /> </div> </form> <?php if (isset($_REQUEST ['q'])) { $query = htmlentities($_REQUEST ['q']); if (strlen($query) < 1) echo "You didn't type anything!"; else { if (isset($_REQUEST ['page'])) { $page = htmlentities($_REQUEST ['page']); $offset = (($page - 1) * $config['results_per_page']); } else $offset = 0; $result = "http://api.search.live.net/json.aspx?Appid={$config['appid']}&sources=web"; $result .= "&query=" . urlencode("site:" . implode(" OR site:", $config['search_domains']) . " " . $query); $result .= "&Web.Count={$config['results_per_page']}&Web.Offset=$offset"; //echo $result; $result = file_get_contents($result); $result = json_decode($result); echo('<ul ID="resultList">'); foreach ($result->SearchResponse->Web->Results as $value) { echo('<li class="resultlistitem"><a href="' . $value->Url . '">'); echo('<h3>' . $value->Title . '</h3></a>'); echo('<p>' . $value->Description . '</p>'); } echo("</ul>"); // echo("<pre>"); // print_r($result); // echo("</pre>"); $results = $result->SearchResponse->Web->Total > 1000 ? 1000 : $result->SearchResponse->Web->Total; if ($results > 0) echo $results . " results <br />\n"; else echo "Sorry, no results to display. <br />\n"; $pages = (int) ($results / $config['results_per_page']); // echo "$pages pages <br />\n"; // pagination // echo "Page #s:<br />"; for ($i = 1; $i <= $pages; $i++) { echo "<a href=$url?q=$query&page=$i>$i</a> "; } } } ?> <?php include('footer.php'); ?> |
Leave a Reply