为什么我的代码没有正确解析这个XML文件?

时间:2010-12-17 01:13:56

标签: php xml xml-parsing

我正在尝试用PHP解析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文件中提取所有数据?如何循环日志文件以提取所有数据?我也希望从行动中获得M.

我也尝试过这段代码,但我无法让它适用于整个文件。

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

echo $xml->getName();


foreach($xml->children() as $child)
  {
    echo $child->getName() . ": " . $child . "<br />";
  }

2 个答案:

答案 0 :(得分:3)

您可以将simplexml用于此目的

$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;
}

答案 1 :(得分:0)

使用PHP的DOMDocument课程。