Php: parsing table structure using SimpleXML

I am trying to read in an XML file that for some reason was modeled in a table structure like this:

<tr id="1"> <td name="Date">10/01/2009</td> <td name="PromoName">Sample Promo Name</td> <td name="PromoCode">Sample Promo Code</td> <td name="PromoLevel" /> </tr> 

This is just one sample line, the file has several <tr> blocks, and they are all surrounded by <table> .

How can I read the values ​​with all lines named <td> name ?

+4
source share
1 answer

You can use simpleXML with an XPath expression.

 $xml = simplexml_load_file('myFile.xml'); $values = $xml->xpath('//td[@name]'); foreach($values as $v) { echo "Found $v<br />"; } 

This will give you all the TD node values ​​that have a name attribute, for example.

 Found 10/01/2009 Found Sample Promo Name Found Sample Promo Code Found <nothing cuz PromoLevel is empty> 

Change To go through all the rows of the table, you can do something like this:

 $rows = $xml->xpath('//tr'); foreach($rows as $row) { echo $row['id']; foreach($row->td as $td) { if($td['name']) { echo $td['name'],':',$td,'<br/>',PHP_EOL; } } } 

You can also see this article .

Edit Fixed XPath expression as suggested by Josh.

+4
source

All Articles