Skip to content

Instantly share code, notes, and snippets.

@mohammadmursaleen
Created September 9, 2016 12:58
Show Gist options
  • Save mohammadmursaleen/9d3acb1642b7c561ca7c064f4f03d069 to your computer and use it in GitHub Desktop.
Save mohammadmursaleen/9d3acb1642b7c561ca7c064f4f03d069 to your computer and use it in GitHub Desktop.
PHP based Google CSE XML Parsed Reponse
<?php
$no_result = true;
// Getting XML Response
if(isset($_GET['q'])){ // Assuming we have got some search query by get method at q index
$query = $_GET['q'];
$api_key = 'your_api_key';
$xml_request = "https://www.google.com/cse?cx=".$api_key."&q=".$query."&output=xml";
$xml_response = file_get_contents($xml_request);
$xml = simplexml_load_string($xml_response);
if ($xml === false) {
$no_result = true;
} else {
$no_result = false;
}
}
// Displaying Reponse if any
if( ! $no_result ){
// Display result count
echo '<p>' . count($xml->RES->R) . ' Matches</p>';
// Display all results
foreach($xml->RES->R as $result) {
if($result->T){
foreach($result->T as $title){
echo '<p><strong>'.$title.'</strong></p>';
}
}
if($result->S) {
foreach ($result->S as $string) {
echo '<p>'.$string.'</p>';
}
}
if($result->U) {
foreach ($result->U as $url) {
echo '<p><a href="'.$url.'">'.$url.'</a></p><br>';
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment