在php中的函数中使用cURL时未定义的变量

时间:2012-10-31 20:59:38

标签: php curl

我正在研究一个简单的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;
}
?>

1 个答案:

答案 0 :(得分:0)

有多种方法可以做到这一点(包括使用global,这往往会使事情变得混乱),但最好的方法是将变量作为参数传递。

更改函数的参数:

function getNumber($name, $tagId) {

当你调用该函数时,传递你的变量:

getNumber($names[0], $resultTagId)