代码之家  ›  专栏  ›  技术社区  ›  TheNone Nabster

simpleXML和同一个孩子

  •  0
  • TheNone Nabster  · 技术社区  · 15 年前

    我有这样一个伪xml:

    <SOA>
    <cities>
        <area>Area1</area>
        <period>period1</period>
        <center>center1</center>
    </cities>
    <cities>
        <area>Area1</area>
        <period>period1</period>
        <center>center2</center>
    </cities>
    <cities>
        <area>Area2</area>
        <period>period1</period>
        <center>center3</center>
    </cities>
    </SOA>
    

    我想在xml中循环,我的问题是:如何循环子对象?e、 g在区域中循环,区域名称是Area1(有两个区域1和中心1和中心2,我想做一个这样的查询:查找所有中心区域1) 提前谢谢

    2 回复  |  直到 15 年前
        1
  •  4
  •   VolkerK    15 年前

    <水晶球> 也许你想迭代所有 cities 具有 area 包含文本内容的元素 Area1
    XPath 为此,例如。

    <?php
    $soa = getDoc();
    foreach( $soa->xpath('cities[area="Area1"]') as $ci ) {
      foreach( $ci->children() as $child ) {
        echo $child->getName(), ': ', (string)$child, "\n";  
      }
    }
    
    function getDoc() {
      return new SimpleXMLElement('<SOA>
        <cities>
          <area>Area1</area>
          <period>period1</period>
          <center>center1</center>
        </cities>
        <cities>
          <area>Area1</area>
          <period>period1</period>
          <center>center2</center>
        </cities>
        <cities>
          <area>Area2</area>
          <period>period1</period>
          <center>center3</center>
          </cities>
        </SOA>');
    }
    

    area: Area1
    period: period1
    center: center1
    area: Area1
    period: period1
    center: center2
    
        2
  •  2
  •   Tomasz Struczyński    15 年前

    http://php.net/manual/en/simplexmlelement.xpath.php

    $xml = new SimpleXMLElement($yourXML);
    
    $result = $xml->xpath('/SOA/cities/SOA/cities[area="Area1"]');
    
    while(list( , $node) = each($result)) {
        //$node is a city node with Area1 area
    }
    
    推荐文章