1

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

1 回答 1

0

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

更改函数的参数:

function getNumber($name, $tagId) {

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

getNumber($names[0], $resultTagId)
于 2012-10-31T21:01:43.180 回答