I know how we can use the Google API to return image results in AJAX, but I want to be able to return images for a specific query and then output them in to HTML using Curl and PHP on my page.
This query is an example.
We want this to return in HTML so we can out put it on the page eg.:
<img src="<?php echo('googleimage'); ?>"/>
We are using this on WordPress and we want MYQUERY to be the title of the page/post the user is on. Please help!
I’ve tried:
<?php
$posttit = get_the_title();
function get_url_contents($url) {
$crl = curl_init();
curl_setopt($crl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
curl_setopt($crl, CURLOPT_URL, $url);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, 5);
$ret = curl_exec($crl);
curl_close($crl);
return $ret;
}
$json = get_url_contents('http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q='.$posttit);
$data = json_decode($json);
foreach ($data->responseData->results as $result) {
$results[] = array('url' => $result->url, 'alt' => $result->title);
}
?>
<?php foreach($results as $image): ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>"/>
<?php endforeach; ?>
Your problem is this line:
Which should read:
However, your
$tit
variable (you are strongly recommended to not hog 3-chars-or-less variable names. The more expressive they are, the easier code is to maintain) is not accessible within the scope of thefunction
. You can pass it as a parameter, or you can useglobal $tit;
inside the function to hoist it inside your scope.The second option, while “it works”-worthy, is very strongly recommended against, as it forces you to pollute the global namespace to use your function, and could lead to a lot of chaos in case you ever decide to use
curl_multi
(multi is asynchronous).