我正在尝试在函数中传递变量以在url中回显时进行解析,但是我收到错误消息说它未定义。变量$ plex_token。
function getPlexXML($url)
{
libxml_use_internal_errors(true);
$plex_token = 'xxxxxxxxxx';
$xml = simplexml_load_file($url);
$count = number_format((float)$xml['totalSize']);
if (false === $xml) {
echo '<div class="counter_offline">N/A</div>';
} else {
echo '<div class="counter_live">'.$count.'</div>';
}
}
echo getPlexXML('https://plex.example.com/library/sections/5/all?type=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0&X-Plex-Token='.$plex_token.'');
答案 0 :(得分:1)
这是因为您在$ plex_token定义的上下文之外引用它。
您在函数“ getPlexXML”中定义了它,但随后在该函数之外使用了它作为传递到getPlexXML的参数。
您可以执行以下操作之一:
A)在函数外部定义它,因为您没有在函数中使用它:
$plex_token = 'xxxxxxxxx';
function getPlexXML($url){
// You cannot use $plex_token in here
...
}
echo getPlexXML('https://plex.example.com/library/sections/5/all?type=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0&X-Plex-Token='.$plex_token.'');
OR B)将其设为全局变量,然后可以在函数内部或外部使用它:
$plex_token = 'xxxxxxxxx';
function getPlexXML($url){
global $plex_goken;
// You can use $plex_token in here
...
}
echo getPlexXML('https://plex.example.com/library/sections/5/all?type=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0&X-Plex-Token='.$plex_token.'');