php: parsing table structure with SimpleXML

☆樱花仙子☆ 提交于 2019-12-07 11:14:51

问题


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:


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.



来源:https://stackoverflow.com/questions/1730428/php-parsing-table-structure-with-simplexml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!