我正在使用Alexa XML API来获取网站流量排名数据。我正在使用以下api请求获取有关网站的信息说facebook.com:
http://data.alexa.com/data?cli=10&dat=snbamz&url==www.facebook.com
我收到以下xml数据:
<!-- Need more Alexa data? Find our APIs here: https://aws.amazon.com/alexa/
-->
<ALEXA VER="0.9" URL="facebook.com/" HOME="0" AID="=" IDN="facebook.com/">
<RLS PREFIX="http://" more="0">
<RL HREF="www.zynga.com/" TITLE="Zynga Inc."/>
<RL HREF="www.zoominfo.com/" TITLE="ZoomInfo"/>
<RL HREF="www.zoho.com/" TITLE="Zoho"/>
<RL HREF="www.ziply.com/" TITLE="Ziply"/>
<RL HREF="www.zillow.com/" TITLE="Zillow"/>
<RL HREF="www.ziki.com/" TITLE="Ziki.com"/>
<RL HREF="www.zazzle.com/" TITLE="Zazzle, Inc."/>
<RL HREF="www.youtube.com/" TITLE="YouTube"/>
<RL HREF="www.yonja.com/" TITLE="Yonja"/>
<RL HREF="www.yelp.com/" TITLE="Yelp"/>
</RLS>
<SD TITLE="A" FLAGS="" HOST="facebook.com">
<TITLE TEXT="Facebook"/>
<OWNER NAME="TheFacebook, Inc."/>
</SD>
<SD>
<POPULARITY URL="facebook.com/" TEXT="3" SOURCE="panel"/>
<REACH RANK="3"/>
<RANK DELTA="+0"/>
<COUNTRY CODE="US" NAME="United States" RANK="3"/>
</SD>
</ALEXA>
我试图在函数simplexml_load_file()的帮助下解析这个xml数据,但它似乎没有用。
我的代码:
function alexa_rank($url){
$xml = simplexml_load_file("http://data.alexa.com/data?cli=10&dat=snbamz&url=".$url);
if(isset($xml->SD)):
return $xml->SD->POPULARITY->attributes();
endif;
}
$url = "www.facebook.com";
echo alexa_rank($url);
我收到以下错误:
Warning: SimpleXMLElement::__toString(): Node no longer exists...
但是当我删除额外的属性&#34; &dat=snbamz
&#34;从查询字符串,然后它的工作原理。为什么呢?
答案 0 :(得分:1)
XML中有2个<SD>
元素,<POPULARITY>
仅在第二个元素中定义。如果情况总是这样,那么您可以将返回更改为
return $xml->SD[1]->POPULARITY->attributes();
(当数组从0开始时,[1]
将返回第二个元素。)
如果你不知道它可能在何时/何地,你应该使用XPath来找到它......
$popularity = $xml->xpath("//SD/POPULARITY")[0];
第二部分是您返回SimpleXMLElements列表,因此使用json_encode()
和json_decode()
将数据转换为数组可能更容易。所以我建议你使用这段代码......
function alexa_rank($url){
$xml = simplexml_load_file("http://data.alexa.com/data?cli=10&dat=snbamz&url=".$url);
$popularity = $xml->xpath("//SD[POPULARITY]")[0];
return json_decode(json_encode($popularity),true);
}
$url = "www.facebook.com";
print_r( alexa_rank($url));
(使用print_r()
,因为你有一个从alexa_rank()
回来的数组
对于您上面提供的数据,此输出......
Array
(
[POPULARITY] => Array
(
[@attributes] => Array
(
[URL] => facebook.com/
[TEXT] => 3
[SOURCE] => panel
)
)
[REACH] => Array
(
[@attributes] => Array
(
[RANK] => 3
)
)
[RANK] => Array
(
[@attributes] => Array
(
[DELTA] => +0
)
)
[COUNTRY] => Array
(
[@attributes] => Array
(
[CODE] => US
[NAME] => United States
[RANK] => 3
)
)
)