使用XPath搜索和打印XML

时间:2012-02-01 13:16:12

标签: php xml xpath

我正在搜索一个如下所示的xml文件:

<producers>
  <producer>
    <name></name>
    <owner></owner>
    <phone></phone>
    <fax></fax>
    <overview></overview>
    <address>
      <civic></civic>
      <mailing></mailing>
      <town></town>
      <province></province>
      <postal></postal>
      <email></email>
      <website></website>
    </address>
    <products>
      <product>Salmon</product>
      <product>Trout</product>
    </products>
    <exports>
      <region>Canada</region>
      <region>United States</region>
    </exports>
  </producer>

然后我像这样搜索它:

$upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZÀÂÆÇÈÉÊËÎÏÔŒÙÛÜ"; 
$lower = "abcdefghijklmnopqrstuvwxyzàâæçèéêëîïôœùûü";

$region = "Canada";

$node = $xml->xpath('//producers/producer/exports[descendant::*[contains(translate(text(), "'.$upper.'", "'.$lower.'"), "'.$region.'")]]');

问题是我希望能够打印整个制作人。但此时我所能获得的只是出口的任何后代所包含的内容。有没有办法可以返回几个节点来检索所需生产者的完整列表?

2 个答案:

答案 0 :(得分:1)

我认为你只需要将/../../放在xpath的末尾。像这样的东西

$node = $xml->xpath('//producers/producer/exports[descendant::*[contains(translate(text(), "'.$upper.'", "'.$lower.'"), "'.$region.'")]]/../../');

答案 1 :(得分:1)

您可以使用此XPath,它更具可读性:

$node = $xml->xpath('//producers/producer[exports/region[contains(translate(text(), "'.$upper.'", "'.$lower.'"), "'.$region.'")]]');

它会选择所需的producer