溫馨提示×

php xpath如何返回特定屬性

PHP
小樊
84
2024-07-21 04:16:55
欄目: 編程語言

要返回特定屬性,您可以使用如下的XPath表達(dá)式:

$doc = new DOMDocument();
$doc->load('file.xml');

$xpath = new DOMXPath($doc);

// 返回具有特定屬性的元素
$elements = $xpath->query('//element[@attribute="value"]');

// 遍歷返回的元素
foreach ($elements as $element) {
    // 處理每個元素
    $attributeValue = $element->getAttribute('attributeName');
    echo $attributeValue;
}

在上面的代碼中,//element[@attribute="value"]表示選擇具有attribute屬性且屬性值為value的元素。您可以將attribute替換為要匹配的屬性名稱,value替換為要匹配的屬性值。然后,您可以使用getAttribute('attributeName')方法來獲取特定屬性的值。

0