什么是"$ ns"?和"$ is_prefix"参数有关? [英] What are the "$ns" and "$is_prefix" parameters about?

查看:128
本文介绍了什么是"$ ns"?和"$ is_prefix"参数有关?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SimpleXMLElement::__construct()方法和相关功能 simplexml_load_file() 都有可选与XML名称空间有关的一对参数:$ns$is_prefix.

尽管我可以看到它们与XML名称空间有关,但我想知道它们的用途以及工作方式.

Despite I can see that those are related to XML namespaces I wonder what they are for and how they work.

推荐答案

根据PHP手册,这两个参数已在PHP 5.2版中添加.正式的PHP 5更改日志未明确记录这些更改,但是 PHP 5.2更新自述文件具有这些更改.

According to PHP manual, those two parameters have been added in PHP version 5.2. The official PHP 5 changelog does not note these changes explicitly but the PHP 5.2 update readme has these.

然后查看5.2构造函数的源代码( )表明它与迭代器有关:

Then looking into the 5.2 source for the constructor (in lxr) it shows that this is related to the iterator:

sxe->iter.nsprefix = ns_len ? xmlStrdup((xmlChar *)ns) : NULL;
sxe->iter.isprefix = isprefix;

因此,我假设这两个参数指定了 SimpleXMLElement 默认将在上进行迭代的XML命名空间.进行一些测试即可验证这一点:

So I assume those two specify the XML Namespace that SimpleXMLElement will iterate over by default. A little test can verify this:

$xml = new SimpleXMLElement(
    '<root><a/><b/><c/></root>'
);

var_dump(count(iterator_to_array($xml))); #int(3)

默认情况下,迭代器在此处具有三个元素:a,b和c.现在将指定迭代的参数设置为与默认名称不同的XML命名空间,从而改变了这一点:

By default, the iterator has three elements here: a, b and c. Now setting the parameters specifying the iteration to be over a different XML-Namespace than the default one changes this:

$xml = new SimpleXMLElement(
    '<root><a/><b/><c/></root>', 0, FALSE, "ns:1"
);

var_dump(count(iterator_to_array($xml))); #int(0)

该迭代现在具有零个元素,因为URI ns:1的命名空间中的根元素没有任何子元素.

The iteration now has zero elements because the root-element does not have any child-elements in the namespace of URI ns:1.

将根元素的名称空间更改为ns:1会再次显示三个元素,因为现在这三个子元素都位于该名称空间中,它们从其父元素继承该元素:

Changing the namespace of the root element to ns:1 will again reveal three elements because now those three child-elements are in that namespace, they inherit it from their parent:

$xml = new SimpleXMLElement(
    '<root xmlns="ns:1"><a/><b/><c/></root>', 0, FALSE, "ns:1"
);

var_dump(count(iterator_to_array($xml))); #int(3)

就像子代本身在该参数对指定的名称空间中一样,并通过这些元素上的前缀:

Same as if the children itself are in the namespace specified by that parameter pair and via a prefix on these elements:

$xml = new SimpleXMLElement(
    '<root xmlns:n="ns:1"><n:a/><n:b/><n:c/></root>', 0, FALSE, "ns:1"
);

var_dump(count(iterator_to_array($xml))); #int(3)

这篇关于什么是"$ ns"?和"$ is_prefix"参数有关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆