Im working on a simple php script that will return the number of search results from google search on a specific string (using cURL). When i keep my code global everything works fine but as soon as i create a function I get an error
Notice: Undefined variable: resultTagId in C:\wamp\www\tag.php on line 24
Notice: Trying to get property of non-object in C:\wamp\tag.php on line 24
here is my code
<?php
$resultTagId = "resultStats";
$encodedNames = $_GET['names'];
$names=json_decode($encodedNames);
getNumber($names[0]);
function getNumber($name) // before i used to set $name = $names[0] and everything worked fine
{
$name = str_replace(" ", "+", trim($name));
$url='http://www.google.com/search?q='.$name.'&ie=utf-8&oe=utf-8&aq=t';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$dom = new DOMDocument();
@$dom->loadHTML( $data );
$resultsTag = $dom->getElementById($resultTagId)->nodeValue;
$results = preg_replace("/[^0-9]/","" ,$resultsTag);
echo $results;
}
?>
There are a variety of ways that you can do this (including using a global, which tends to make things messy), but the best way is to pass your variable as an argument.
Change the arguments for the function:
And when you’re calling the function, pass your variable: