PHP:获取xml的属性值

时间:2012-02-06 14:44:37

标签: php xml xpath

我有以下xml结构:

<stores>
   <store>
      <name></name>
      <address></address>
      <custom-attributes>
          <custom-attribute attribute-id="country">Deutschland</custom-attribute>
          <custom-attribute attribute-id="displayWeb">false</custom-attribute>
      </custom-attributes>
   </store>
</stores>

我怎样才能获得“displayWeb”的价值?

4 个答案:

答案 0 :(得分:2)

最佳解决方案是使用PHP DOM,您可以循环使用所有商店:

$dom = new DOMDocument();
$dom->loadXML( $yourXML);

// With use of child elements:
$storeNodes = $dom->documentElement->childNodes;

// Or xpath
$xPath = new DOMXPath( $dom);
$storeNodes = $xPath->query( 'store/store');

// Store nodes now contain DOMElements which are equivalent to this array:
// 0 => <store><name></name>....</store>
// 1 => <store><name>Another store not shown in your XML</name>....</store>

这些用途DOMDocument propertiesDOMElement属性childNodesDOMXPath。拥有所有商店后,您可以使用foreach循环遍历它们并获取所有元素并将其存储到getElementsByTagName的关联数组中:

foreach( $storeNodes as $node){
  // $node should be DOMElement
  // of course you can use xPath instead of getAttributesbyTagName, but this is
  // more effective
  $domAttrs = $node->getAttributesByTagName( 'custom-attribute');
  $attributes = array();
  foreach( $domAttrs as $domAttr){
    $attributes[ $domAttr->getAttribute( 'attribute-id')] = $domAttr->nodeValue;
  }
  // $attributes = array( 'country' => 'Deutschland', 'displayWeb' => 'false');
}

或直接使用xPath选择属性:

// Inside foreach($storeNodes as $node) loop 
$yourAttribute = $xPath->query( "custom-attribute[@attribute-id='displayWeb']", $node)
     ->item(0)->nodeValue; // Warning will cause fatal error when missing desired tag

或者当您只需要整个文档中的一个值时(如Kirill Polishchuk建议的那样):

$yourAttribute = $xPath->query( "stores/store/custom-attributes/custom-attribute[@attribute-id='displayWeb']")
    ->item(0)->nodeValue; // Warning will cause fatal error when missing desired tag

仔细阅读手册,了解在何时以及包含哪些属性时返回的类型。

答案 1 :(得分:1)

例如,我可以解析XML DOM。 http://php.net/manual/en/book.dom.php

答案 2 :(得分:1)

您可以使用XPath:

stores/store/custom-attributes/custom-attribute[@attribute-id='displayWeb']

答案 3 :(得分:1)

我建议PHP's SimpleXML。该网页有许多用户提供的用于从解析数据中提取值的示例。