【问题标题】:PHP: get attributes value of xmlPHP:获取xml的属性值
【发布时间】:2012-02-28 00:45:24
【问题描述】:

我有以下 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”的值?

【问题讨论】:

  • 没有条件,我只想得到值“false”

标签: php xml xpath


【解决方案1】:

最好的解决方案是使用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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您可以使用 XPath:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

        • 你也有这个案例的具体例子吗?
        猜你喜欢
        • 1970-01-01
        • 2012-10-16
        • 2022-01-13
        • 2021-04-30
        • 1970-01-01
        • 1970-01-01
        • 2011-07-26
        • 2016-08-01
        • 1970-01-01
        相关资源
        最近更新 更多