Tweet
Tweet

Reputation: 678

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)
  {
    echo $child->getName() . ": " . $child . "<br />";
  }

Upvotes: 1

Views: 219

Answers (2)

RageZ
RageZ

Reputation: 27323

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

Upvotes: 3

Geoffrey
Geoffrey

Reputation: 5432

Use PHP's DOMDocument class.

Upvotes: 0

Related Questions