1

好的,我有一些基本的 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);

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

  1. ID
  2. 钥匙
  3. 地址
  4. 城市
  5. 状态
  6. 压缩

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

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

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

4

2 回答 2

0

您可以使用 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";
   }
于 2012-08-10T06:46:05.500 回答
0

好的,所以我查看了您的建议(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

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

于 2012-08-10T11:20:48.600 回答