[DOC-CVS] [doc-en] master: SimpleXML: Add namespace example
[email protected] (Jakub Vrana)
| Newsgroups | php.doc.cvs |
|---|---|
| Message-ID | <[email protected]> |
Author: Jakub Vrana (vrana)
Date: 2025-04-19T09:33:55+02:00
Commit: https://github.com/php/doc-en/commit/8ac065774e87c73919ee3508fc957adebe1c4408
Raw diff: https://github.com/php/doc-en/commit/8ac065774e87c73919ee3508fc957adebe1c4408.diff
SimpleXML: Add namespace example
Changed paths:
M reference/simplexml/examples.xml
Diff:
diff --git a/reference/simplexml/examples.xml b/reference/simplexml/examples.xml
index eb2575388c4a..b2af9b257f63 100644
--- a/reference/simplexml/examples.xml
+++ b/reference/simplexml/examples.xml
@@ -412,6 +412,49 @@ blah
</screen>
</example>
</para>
+ <para>
+ <example>
+ <title>Working with namespaces</title>
+ <programlisting role="php">
+<![CDATA[
+<?php
+$data = <<<XML
+<movies xmlns="http://default" xmlns:a="http://a">
+ <movie xml:id="movie1" a:link="IMDB">
+ <a:actor>Onlivia Actora</a:actor>
+ </movie>
+</movies>
+XML;
+
+$movies = simplexml_load_string($data);
+
+// Namespace http://www.w3.org/XML/1998/namespace is available as "xml".
+echo $movies->movie->attributes("xml", true)["id"] . "\n";
+
+// Namespaced attributes can be accessed with attributes().
+echo $movies->movie->attributes("a", true)["link"] . "\n";
+
+// Using namespace URI allows document to use any namespace alias.
+echo $movies->movie->attributes("http://a")["link"] . "\n";
+
+// Children can be accessed with children().
+echo $movies->movie->children("http://a")->actor . "\n";
+
+// Using xpath() with namespace requires registering it first.
+$movies->registerXPathNamespace("a", "http://a");
+echo count($movies->xpath("//a:actor")) . "\n";
+
+// Even the default namespace must be registered.
+$movies->registerXPathNamespace("default", "http://default");
+echo count($movies->xpath("//default:movie")) . "\n";
+
+// This is empty.
+echo count($movies->xpath("//movie")) . "\n";
+?>
+]]>
+ </programlisting>
+ </example>
+ </para>
</section>
<section xml:id="simplexml.examples-errors">