我正在研究一个简单的 php 脚本,它将返回来自谷歌搜索特定字符串的搜索结果的数量(使用 cURL)。当我将代码保持在全局范围内时,一切正常,但是一旦创建函数,就会出现错误
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
这是我的代码
<?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;
}
?>