PHP registerXPathNamespace() 函數
實例
為下一個 XPath 查詢創建命名空間上下文:
<?php
$xml=<<<XML
<book xmlns:chap="http://example.org/chapter-title">
<title>My Book</title>
<chapter id="1">
<chap:title>Chapter 1</chap:title>
<para>Donec velit. Nullam eget tellus...</para>
</chapter>
<chapter id="2">
<chap:title>Chapter 2</chap:title>
<para>Lorem ipsum dolor sit amet....</para>
</chapter>
</book>
XML;
$sxe=new SimpleXMLElement($xml);
$sxe->registerXPathNamespace('c','http://example.org/chapter-title');
$result=$sxe->xpath('//c:title');
foreach ($result as $title)
{
echo $title . "<br>";
}
?>
$xml=<<<XML
<book xmlns:chap="http://example.org/chapter-title">
<title>My Book</title>
<chapter id="1">
<chap:title>Chapter 1</chap:title>
<para>Donec velit. Nullam eget tellus...</para>
</chapter>
<chapter id="2">
<chap:title>Chapter 2</chap:title>
<para>Lorem ipsum dolor sit amet....</para>
</chapter>
</book>
XML;
$sxe=new SimpleXMLElement($xml);
$sxe->registerXPathNamespace('c','http://example.org/chapter-title');
$result=$sxe->xpath('//c:title');
foreach ($result as $title)
{
echo $title . "<br>";
}
?>
定義和用法
registerXPathNamespace() 函數為下一個 XPath 查詢創建命名空間上下文。
如果在 XML 文檔中改變命名空間首碼,這個函數很有用。registerXPathNamespace()函數將創建一個指定的命名空間首碼,使受影響的 XML 節點可以在不改變應用程式代碼太多的情況下進行訪問。
語法
registerXPathNamespace(prefix,ns);
| 參數 | 描述 |
|---|---|
| prefix | 必需。規定在 ns 指定的命名空間的 XPath 查詢中使用的的命名空間首碼。 |
| ns | 必需。規定用於 XPath 查詢的命名空間。 |
技術細節
| 返回值: | 如果成功則返回 TRUE,如果失敗則返回 FALSE。 |
|---|---|
| PHP 版本: | 5.2+ |
PHP SimpleXML 參考手冊
