Php 为二级XML节点提取名称/值对

Php 为二级XML节点提取名称/值对,php,xml,loops,simplexml,extract,Php,Xml,Loops,Simplexml,Extract,好的,我有以下格式的一些基本XML: <application> <authentication> <id>26</id> <key>gabe</key> </authentication> <home> <address>443 Pacific Avenue</address> <city>Nort

好的,我有以下格式的一些基本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>
我想提取第二个节点的名称/值对,例如,我想忽略
节点。我只对这些第一级节点中的子节点感兴趣:

  • 身份证
  • 钥匙
  • 地址
  • 城市
  • 陈述
  • 拉链
  • 因此,我正在寻找一个foreach循环,它将提取出上述6个名称/值对,但忽略“较低级别”的名称/值对。下面的代码只打印
    节点的名称/值对(我想忽略它):

    有人能帮我找出只提取上述6个节点的名称/值对的代码吗?

    您可以使用xpath:

    用这条路

    /application/*/*
    
    您将获得所有二级元素

    编辑:


    $string=好的,所以我回顾了你的建议(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";
    }
    

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

    我仍然无法提取第二级元素的对应名称,只有值。请参阅下面的答案。xpath返回简单的xml元素。如果将它们用作字符串,则只能看到内部值,但yu可以对它们使用对象方法。尝试“$node->getName()”
    /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";
       }
    
    $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