PHP SimpleXML函数

PHP SimpleXMLElement::registerXPathNamespace() 方法为下一个 XPath 查询创建一个 prefix/ns 上下文。特别是,如果给定 XML 文档的提供者更改名称空间前缀,这会很有帮助。 registerXPathNamespace 将为关联的命名空间创建一个前缀,允许访问该命名空间中的节点,而无需更改代码以允许提供程序指定的新前缀。

语法

public SimpleXMLElement::registerXPathNamespace(prefix, namespace) 

参数

prefix必填。 指定在 namespace 中给定的命名空间的 XPath 查询中使用的命名空间前缀。
namespace 必填。 指定用于 XPath 查询的命名空间。它必须与 XML 文档使用的命名空间匹配,否则使用 prefix 的 XPath 查询将不会返回任何结果。

返回值

成功时返回 true,失败时返回 false。

示例:设置在 XPath 查询中使用的命名空间前缀

下面的示例显示了SimpleXMLElement::registerXPathNamespace() 方法。

<?php
$xmlstr = <<<XML
<book xmlns:chap="https://example.com/chapter-title">
  <title>My Book</title>
  <chapter id="1">
    <chap:title>Chapter 1</chap:title>
    <para>This is chapter 1 content.</para>
  </chapter>

  <chapter id="2">
    <chap:title>Chapter 2</chap:title>
    <para>This is chapter 2 content.</para>
  </chapter>
</book> 
XML;

$xml = new SimpleXMLElement($xmlstr);

$xml->registerXPathNamespace('d', 'https://example.com/chapter-title');
$result = $xml->xpath('//d:标题');

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

上述代码的输出将是:

Chapter 1
Chapter 2 

请注意,上例中显示的 XML 文档如何设置前缀为 chap 的命名空间。想象一下,这个文档(或另一个类似的文档)过去可能使用过 d 前缀来表示同一名称空间。由于它已更改,XPath 查询将不再返回正确的结果,并且查询将需要修改。使用 registerXPathNamespace() 方法可以避免将来修改查询,即使提供程序更改命名空间前缀也是如此。