4

I'm trying to read in an xml file that for some reason has been modeled in a table structure like so:

<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 row, the file has multiple <tr> blocks and it's all surrounded by <table>.

How can I read in the values, with all of the lines being named <td> name?

1 Answer 1

4

You could 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 would give you all the TD node values that have a name attribute, e.g.

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

Edit To get through all the Table Rows, you could 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 might also want to have a look at this article.

Edit Fixed the XPath expression, as Josh suggested.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.