10

我正在使用 PHP 阅读一些 XML,并且目前正在使用DOMDocument该类来执行此操作。我需要一种方法来获取标签(的实例DOMElement)属性的名称和值,而无需事先知道它们是什么。该文档似乎没有提供类似的东西。我知道如果我有一个属性的名称,我可以得到它的值,但同样,我不知道其中任何一个,需要找到两者。

我也知道其他类似的类也SimpleXMLElement具有此功能,但我对如何使用DOMDocument.

4

3 回答 3

27

如果要获取属性名称和属性值(而不是属性节点),则必须调用 DOMNode 对象的 $attrNode->nodeValue 属性。

$attributes = array();

foreach($element->attributes as $attribute_name => $attribute_node)
{
  /** @var  DOMNode    $attribute_node */
  $attributes[$attribute_name] = $attribute_node->nodeValue;
}
于 2010-02-08T19:20:52.940 回答
16

您可以使用DomNode->attributes属性获取给定 DomNode 的所有属性,它将返回包含属性名称和值的DOMNamedNodeMap 。

foreach ($node->attributes as $attrName => $attrNode) {
    // ...
}
于 2009-08-27T03:27:30.547 回答
0

我在寻找将节点属性转换为数组以便将该数组与数据库结果进行比较的方法时偶然发现了这个问题。来自https://stackoverflow.com/users/264502/jan-molak的回答确实可以解决问题,但就我而言,它并不能说明节点中可能缺少某些属性或它们可能是空字符串的事实, 而有NULL从 DB 返回的 s。
为了涵盖这一点,我已将其扩展为以下功能,这也可能对其他人有用:

    #Function to convert DOMNode into array with set of attributes, present in the node
    #$null will replace empty strings with NULL, if set to true
    #$extraAttributes will add any missing attributes as NULL or empty strings. Useful for standartization
    public function attributesToArray(\DOMNode $node, bool $null = true, array $extraAttributes = []): array
    {
        $result = [];
        #Iterrate attributes of the node
        foreach ($node->attributes as $attrName => $attrValue) {
            if ($null && $attrValue === '') {
                #Add to resulting array as NULL, if it's empty string
                $result[$attrName] = NULL;
            } else {
                #Add actual value
                $result[$attrName] = $attrValue->textContent;
            }
        }
        #Add any additional attributes, that are expected
        if (!empty($extraAttributes)) {
            foreach ($extraAttributes as $attribute) {
                if (!isset($result[$attribute])) {
                    if ($null) {
                        #Add as NULL
                        $result[$attribute] = NULL;
                    } else {
                        #Or add as empty string
                        $result[$attribute] = '';
                    }
                }
            }
        }
        #Return resulting string
        return $result;
    }
}

我已经替换nodeValuetextContent,因为在谈到属性时,不知何故它对我来说感觉更“自然”,但从技术上讲,无论如何它们在这里都是一样的。
如果需要,此功能可在 Composer 中作为Simbiat/ArrayHelpers( https://github.com/Simbiat/ArrayHelpers )的一部分使用

于 2021-09-08T12:48:32.260 回答