Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

php - What are the "$ns" and "$is_prefix" parameters about?

The SimpleXMLElement::__construct() method and the related functions simplexml_load_string() and simplexml_load_file() all have an optional pair of parameters related to XML Namepspaces: $ns and $is_prefix.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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;

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)

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)

The iteration now has zero elements because the root-element does not have any child-elements in the namespace of URI 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...