simplexml_load_file 不会使用数组获取数据

simplexml_load_file won't fetch data with an Array

我正在尝试从 Alexa 排名中获取 xml 数据 url

http://data.alexa.com/data?cli=10&dat=s&url=google.com

这个单个 url 工作正常,但是当我在数组中获得多个 url 并通过 foreach 循环它时,它只显示数组中最后一个 url 的数据。我使用的代码是

$list = file_get_contents("sites.txt");
$urls = explode ("\n", $list);


foreach ($urls as $url) {
echo $url;echo "<br />";
$uri = 'http://data.alexa.com/data?cli=10&dat=s&url=';
$uri .= $url;
$xml = simplexml_load_file($uri,"SimpleXMLElement",LIBXML_NOCDATA);

print_r($xml); 
if (isset($xml->SD[1])){
$data = (int) $xml->SD[1]->POPULARITY->attributes()->TEXT;
print_r($data);
}
else {echo "Not Found";echo "<br />";}  

}

sites.txt 包含

google.com
facebook.com
archive.com
adjustedreality.com
adkforum.com

结果是

google.com 
SimpleXMLElement Object ( [@attributes] => Array ( [VER] => 0.9 [URL] => 404 [HOME] => 0 [AID] => = [IDN] => ) [0] => ) Not Found
facebook.com 
SimpleXMLElement Object ( [@attributes] => Array ( [VER] => 0.9 [URL] => 404 [HOME] => 0 [AID] => = [IDN] => ) [0] => ) Not Found
archive.com 
SimpleXMLElement Object ( [@attributes] => Array ( [VER] => 0.9 [URL] => 404 [HOME] => 0 [AID] => = [IDN] => ) [0] => ) Not Found
adjustedreality.com 
SimpleXMLElement Object ( [@attributes] => Array ( [VER] => 0.9 [URL] => 404 [HOME] => 0 [AID] => = [IDN] => ) [0] => ) Not Found
adkforum.com
SimpleXMLElement Object ( [@attributes] => Array ( [VER] => 0.9 [URL] => adkforum.com/ [HOME] => 0 [AID] => = [IDN] => adkforum.com/ ) [SD] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [TITLE] => A [FLAGS] => [HOST] => adkforum.com ) [0] => ) [1] => SimpleXMLElement Object ( [POPULARITY] => SimpleXMLElement Object ( [@attributes] => Array ( [URL] => adkforum.com/ [TEXT] => 2054938 [SOURCE] => panel ) ) [REACH] => 
SimpleXMLElement Object ( [@attributes] => Array ( [RANK] => 2100659 ) ) [RANK] => SimpleXMLElement Object ( [@attributes] => Array ( [DELTA] => +800368 ) ) ) ) ) 2054938

sites.txt是2个还是200个url都没有关系,只会显示list/array最后url的数据。

由于您的文件可能包含其他奇怪字符(包括 \r、空格等),因此最好确保您使用 trim()...[=12 清理 URL =]

$uri .= trim($url);