如何使用PHP解析这个xml数据?

时间:2012-01-11 11:19:32

标签: php xml

<?xml version="1.0" encoding="UTF-8"?>
<ALEXA VER="0.9" URL="infosys.com/" HOME="0" AID="=">

   <RLS PREFIX="http://" more="62">
   <RL HREF="wipro.com/" TITLE="Wipro Corporation"/>
   <RL HREF="tcs.com/" TITLE="Tata Consultancy Services"/>
   <RL HREF="satyam.com/" TITLE="Satyam Computer Services Ltd"/>
   <RL HREF="ibm.com/" TITLE="IBM Corporation"/>
   <RL HREF="rediff.com/" TITLE="Rediff.com India Ltd."/>
   <RL HREF="moneycontrol.com/" TITLE="MoneyControl.com"/>
   <RL HREF="in.com/" TITLE="IN.com"/>
   <RL HREF="google.co.in/" TITLE="Google India"/>
   <RL HREF="www.stiknowledge.com/" TITLE="Business Process Outsourcing | Help Desk    Outsourcing And Certification"/>
   <RL HREF="www.sourcinginterests.org/" TITLE="Sourcing Interests Group"/>
   <RL HREF="www.dice.com/" TITLE="www.dice.com/"/>
   </RLS>
   <SD TITLE="A" FLAGS="DMOZ" HOST="infosys.com">
   <TITLE TEXT="Infosys"/>
   <ADDR STREET=" 44, Electronics City,  Hosur Road" CITY=" Bangalore,  KARNATAKA  560 100" STATE="" ZIP="" COUNTRY=" India" />
   <CREATED DATE="17-Jul-1992" DAY="17" MONTH="07" YEAR="1992"/>
   <PHONE NUMBER="91 80 852 0261"/>
   <OWNER NAME="Infosys Technologies Limited"/>
   <EMAIL ADDR="marketing@infosys.com"/>
   <LANG LEX="en" CODE="us-ascii"/>
   <LINKSIN NUM="2858"/>
  <SPEED TEXT="1308" PCT="55"/>
  <REVIEWS AVG="5.0" NUM="1"/>
  <CHILD SRATING="0"/>
   </SD>

   <KEYWORDS>
   <KEYWORD VAL="Karnataka"/>
   <KEYWORD VAL="Bangalore"/>
   </KEYWORDS><DMOZ>
   <SITE BASE="infosys.com/" TITLE="Infosys" DESC="Infosys (NASDAQ:INFY) defines, designs and delivers IT enabled business solutions. These provide you with strategic differentiation and operational superiority, thereby increasing your competitiveness. Each solution is delivered with the industry-benchmark Infosys Predictability that gives you peace of mind.">
   <CATS>
   <CAT ID="Top/Computers/Software/Consultants" TITLE="Software/Consultants" CID="379688"/>
  <CAT ID="Top/Regional/Asia/India/Karnataka/Localities/Bangalore/Business_and_Economy/Computers_and_Internet/Software" TITLE="Computers and Internet/Software" CID="497626"/>
  </CATS>
  </SITE>
  </DMOZ>
  <SD>
  <POPULARITY URL="infosys.com/" TEXT="15422"/>
  <REACH RANK="17335"/>
  <RANK DELTA="+1"/>
   </SD>
   </ALEXA>

我使用了$ xml = new SimpleXMLElement(&#39; xml data here&#39;) 然后使用          $ X = $ XML-&GT;的xpath(&#39; / ALEXA); 我在这里获得如何访问LINKSIN NUM和REACH RANK。 如果我发送$ x in foreach就像          foreach($ x as $ y){          $ y-&gt; LINKSIN NUM;          } 它将抛出错误,因为LINKSIn和NUM

之间存在差距

2 个答案:

答案 0 :(得分:3)

这应该有效:

$xml = simplexml_load_string($dataHere);
$rank = (int)$xml->SD->REACH['RANK'];

文档:http://nl3.php.net/simplexml_load_string

如果您有xml的URL:

$xml = simplexml_load_file($URL_to_file);

答案 1 :(得分:1)

试试这个:

$xml = simplexml_load_string($xml);
$links = $xml->xpath('//SD/LINKSIN');
$reach = $xml->xpath('//SD/REACH');

$num  = (int)$links[0]['NUM'];
$rank = (int)$reach[0]['RANK'];