使用SimpleXML解析表结构

使用SimpleXML解析表结构

本文介绍了php:使用SimpleXML解析表结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取一个xml文件,该文件由于某种原因已在表结构中建模,如下所示:

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>

这只是一个样本行,该文件有多个< tr> 块,它们全部被< table> 包围。

This is just one sample row, the file has multiple <tr> blocks and it's all surrounded by <table>.

我怎样才能阅读在值中,所有行都命名为< td> name

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

推荐答案

您可以将simpleXML与XPath表达式一起使用。

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

这将为您提供具有name属性的所有TD节点值,例如

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.

编辑修正了XPath表达式,正如Josh建议的那样。

Edit Fixed the XPath expression, as Josh suggested.

这篇关于php:使用SimpleXML解析表结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 04:42