PHP Conference Japan 2024

SimpleXMLElement::registerXPathNamespace

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SimpleXMLElement::registerXPathNamespace 為下一個 XPath 查詢建立前綴/命名空間上下文

說明

public SimpleXMLElement::registerXPathNamespace(字串 $prefix, 字串 $namespace): 布林值

為下一個 XPath 查詢建立前綴/命名空間上下文。尤其在給定 XML 文件的提供者更改命名空間前綴時,這會很有幫助。 registerXPathNamespace 會為相關聯的命名空間建立一個前綴,讓使用者可以存取該命名空間中的節點,而無需更改程式碼以允許提供者指定的新的前綴。

參數

prefix(前綴)

在 XPath 查詢中用於 namespace 中給定命名空間的命名空間前綴。

namespace(命名空間)

用於 XPath 查詢的命名空間。這必須與 XML 文件中使用的命名空間相符,否則使用 prefix 的 XPath 查詢將不會返回任何結果。

返回值

成功時返回 true,失敗時返回 false

範例

範例 #1 設定 XPath 查詢中要使用的命名空間前綴

<?php

$xml
= <<<EOD
<book xmlns:chap="http://example.org/chapter-title">
<title>我的書</title>
<chapter id="1">
<chap:title>第一章</chap:title>
<para>Donec velit. Nullam eget tellus vitae tortor gravida scelerisque.
In orci lorem, cursus imperdiet, ultricies non, hendrerit et, orci.
Nulla facilisi. Nullam velit nisl, laoreet id, condimentum ut,
ultricies id, mauris.</para>
</chapter>
<chapter id="2">
<chap:title>第二章</chap:title>
<para>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin
gravida. Phasellus tincidunt massa vel urna. Proin adipiscing quam
vitae odio. Sed dictum. Ut tincidunt lorem ac lorem. Duis eros
tellus, pharetra id, faucibus eu, dapibus dictum, odio.</para>
</chapter>
</book>
EOD;

$sxe = new SimpleXMLElement($xml);

$sxe->registerXPathNamespace('c', 'http://example.org/chapter-title');
$result = $sxe->xpath('//c:title');

foreach (
$result as $title) {
echo
$title . "\n";
}

?>

以上範例將輸出

Chapter 1
Chapter 2

請注意範例中顯示的 XML 文件如何使用前綴 chap 設定命名空間。假設此文件(或其他類似文件)過去可能曾使用前綴 c 表示相同的命名空間。由於它已更改,XPath 查詢將不再返回正確的結果,並且需要修改查詢。使用 registerXPathNamespace 可避免即使提供者更改命名空間前綴,也無需修改查詢。

參見

新增筆記

使用者貢獻的筆記 1 則筆記

Lea Hayes
13 年前
看起來在使用 XPath 時,您必須為每個節點使用 registerXPathNamespace。

<?php
$xml
= simplexml_load_file($filename);

$xml->registerXPathNamespace('test', 'http://example.com');

$shopping_element = $xml->xpath('test:shopping-list');

// 沒有下面這行會出錯:

$shopping_element->registerXPathNamespace('test', 'http://example.com');

$fruit = $shopping_element->xpath('test:fruit');
?>
To Top