首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PHP:获取xml的属性值

PHP:获取xml的属性值
EN

Stack Overflow用户
提问于 2012-02-06 22:44:37
回答 4查看 1.8K关注 0票数 3

我有以下xml结构:

代码语言:javascript
运行
复制
<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“的值?

EN

回答 4

Stack Overflow用户

发布于 2012-02-06 23:17:24

最好的解决方案是使用PHP DOM,你可以循环遍历所有商店:

代码语言:javascript
运行
复制
$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将它们存储到关联数组中

代码语言:javascript
运行
复制
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选择属性

代码语言:javascript
运行
复制
// 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建议的那样):

代码语言:javascript
运行
复制
$yourAttribute = $xPath->query( "stores/store/custom-attributes/custom-attribute[@attribute-id='displayWeb']")
    ->item(0)->nodeValue; // Warning will cause fatal error when missing desired tag

仔细阅读手册,了解什么时候返回什么类型,以及哪个属性包含什么。

票数 2
EN

Stack Overflow用户

发布于 2012-02-06 22:48:30

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

票数 1
EN

Stack Overflow用户

发布于 2012-02-06 22:58:10

您可以使用XPath:

代码语言:javascript
运行
复制
stores/store/custom-attributes/custom-attribute[@attribute-id='displayWeb']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9161866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档