I am trying to fetch xml data from Alexa Ranking url
http://data.alexa.com/data?cli=10&dat=s&url=google.com
this single url works fine but when I get multiple urls in array and loop it through foreach it only shows data of last url in the array. The code I'm using is
$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 />";}
}
the sites.txt contains
google.com
facebook.com
archive.com
adjustedreality.com
adkforum.com
the result is
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
It doesn't matter if the sites.txt contain 2 or 200 urls, it will only shows data of the last url in the list/array.
As your file may contain other odd characters (including \r, spaces etc.), it would be better to ensure you clean up the URL with trim()
...
$uri .= trim($url);