php: parsing table structure with SimpleXML

2019-05-06 13:03发布

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条回答
再贱就再见
2楼-- · 2019-05-06 13:24

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.

查看更多
登录 后发表回答