What are the "$ ns" and "$ is_prefix" options?

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

Despite the fact that I see that they are associated with XML namespaces, I wonder what they are for and how they work.

+4
source share
1 answer

According to the PHP manual, these two parameters were added in PHP version 5.2. The official PHP 5 changelog does not explicitly account for these changes, but reads an update for PHP 5.2.

Then, looking at source 5.2 for the constructor ( in lxr ), it shows that this is due to the iterator:

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

So, I assume that these two define an XML namespace that SimpleXMLElement will rename by default. A small test may confirm this:

 $xml = new SimpleXMLElement( '<root><a/><b/><c/></root>' ); var_dump(count(iterator_to_array($xml))); #int(3) 

By default, an iterator has three elements: a, b, and c. Now setting parameters indicating that the iteration will be in a different XML namespace than the default will change 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 null elements because the root element has no children in the namespace URI ns:1 .

Changing the namespace of the root element to ns:1 will open three elements again, since now these three children are in this 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) 

The same as the children themselves are in the namespace specified by this pair of parameters, and through 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) 
+6
source

Source: https://habr.com/ru/post/1487689/


All Articles