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