开发者

Why doesn't my code properly parse this XML file?

I am trying to parse an xml log file in PHP. It has following structure

 <log>
 <logentry revision="1745">
 <author>abc</author> 
  <date>2010-08-31T20:46:29.691125Z</date> 
 <paths>
  <path kind="" action="M">/trunk/myserver/abc.java</path> 
  <path kind="" action="M">/trunk/myserver/test.java</path> 
  <path kind="" action="M">/trunk/myserver/xmltest.java</path> 
  </paths>
  <msg>how to make it work!</msg> 
  </logentry>
</log>

How can I extract all data from this xml file? How can loop on log file to extract all data? I want to get that M from action as well.

I tried this code as well, but I couldn't make it work for whole file.

$xml = simplexml_load_file("test.log");

echo $xml->getName();


foreach($xml->children() as $child)
  {
  开发者_如何学JAVA  echo $child->getName() . ": " . $child . "<br />";
  }


you can use simplexml for that purpose

$xmlStr = <<<XML
<log>
 <logentry revision="1745">
 <author>abc</author> 
  <date>2010-08-31T20:46:29.691125Z</date> 
 <paths>
  <path kind="" action="M">/trunk/myserver/abc.java</path> 
  <path kind="" action="M">/trunk/myserver/test.java</path> 
  <path kind="" action="M">/trunk/myserver/xmltest.java</path> 
  </paths>
  <msg>how to make it work!</msg> 
  </logentry>
</log>
XML;

$xml = new SimpleXMLElement($xmlStr);
foreach($xml->logentry as $entry){
   echo "revision: {$entry['revision']}" . PHP_EOL;
   echo "author: {$entry->author}" . PHP_EOL;
   echo "paths:" . PHP_EOL;
   foreach($entry->paths->path as $pa){
     echo "\t kind: {$pa['kind']} action: {$pa['action']} path: {$pa}" . PHP_EOL;
   }
   echo "message: {$entry->msg}" . PHP_EOL;
}


Use PHP's DOMDocument class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜