【问题标题】:Extracing name / value pairs for second-level XML nodes提取二级 XML 节点的名称/值对
【发布时间】:2012-08-07 10:59:15
【问题描述】:

好的,我有一些基本的 XML 格式如下:

<application>
   <authentication>
      <id>26</id>
      <key>gabe</key>
   </authentication>
   <home>
      <address>443 Pacific Avenue</address>
      <city>North Las Vegas</city>
      <state>NV</state>
      <zip>89084</zip>
   </home>
</application>

我正在使用simplexml_load_string()将上面的XML加载到一个变量中,如下:

$xml = simplexml_load_string($xml_string);

我想提取第二个节点的名称/值对,例如,我想忽略&lt;authentication&gt;&lt;home&gt; 节点。我只对这些一级节点内的子节点感兴趣:

  1. 身份证
  2. 地址
  3. 城市
  4. 状态
  5. 压缩包

所以我正在寻找一个 foreach 循环,它将提取出上述 6 个名称/值对,但忽略“较低级别”的名称/值对。以下代码仅打印 &lt;authentication&gt;&lt;home&gt; 节点的名称/值对(我想忽略):

foreach($xml->children() as $value) {
  $name = chop($value->getName());
  print "$name = $value";
}

有人可以帮我写出提取上述 6 个节点的名称/值对的代码吗?

【问题讨论】:

    标签: php xml loops simplexml extract


    【解决方案1】:

    好的,所以我查看了您的建议(Oliver A.)并提出了以下代码:

    $string = <<<XML
    <application>
       <authentication>
          <id>26</id>
          <key>gabe</key>
       </authentication>
       <home>
          <address>443 Pacific Avenue</address>
          <city>North Las Vegas</city>
          <state>NV</state>
          <zip>89084</zip>
       </home>
    </application>
    XML;
    
    $xml = new SimpleXMLElement($string);
    
    /* Search for <a><b><c> */
    $result = $xml->xpath('/application/*/*');
    
    while(list( , $node) = each($result)) {
        echo '/application/*/*: ',$node,"\n";
    }
    

    返回以下内容:

    /application/*/*: 26
    /application/*/*: gabe
    /application/*/*: 443 Pacific Avenue
    /application/*/*: North Las Vegas
    /application/*/*: NV
    /application/*/*: 89084
    

    这是进步,因为我现在只有二级元素的值。伟大的!问题是我需要为名称和值对分配一个变量名称。似乎我无法提取每个二级节点的名称。我错过了什么吗?

    【讨论】:

    • xpath 返回简单的 xml 元素。如果您将它们用作字符串,您将只能看到内部值,但您可以对它们使用对象方法。试试“$node->getName()”
    【解决方案2】:

    您可以使用 xpath: http://php.net/manual/en/simplexmlelement.xpath.php

    带路径

    /application/*/*
    

    您将获得所有二级元素。

    编辑:

    $string = <<<XML
    <application>
       <authentication>
          <id>26</id>
          <key>gabe</key>
       </authentication>
           <home>
              <address>443 Pacific Avenue</address>
              <city>North Las Vegas</city>
              <state>NV</state>
              <zip>89084</zip>
           </home>
        </application>
    XML;
    
        $xml = new SimpleXMLElement($string);
    
       foreach($xml->xpath('/application/*/*') as $node){
            echo "{$node->getName()}: $node,\n";
       }
    

    【讨论】:

    • 我仍然无法提取出二级元素的对应名称,只能提取值。请参阅下面的答案。
    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多