Skip to content

Commit 8ac0657

Browse files
committed
SimpleXML: Add namespace example
1 parent ac164c9 commit 8ac0657

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

reference/simplexml/examples.xml

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,49 @@ blah
412412
</screen>
413413
</example>
414414
</para>
415+
<para>
416+
<example>
417+
<title>Working with namespaces</title>
418+
<programlisting role="php">
419+
<![CDATA[
420+
<?php
421+
$data = <<<XML
422+
<movies xmlns="http://default" xmlns:a="http://a">
423+
<movie xml:id="movie1" a:link="IMDB">
424+
<a:actor>Onlivia Actora</a:actor>
425+
</movie>
426+
</movies>
427+
XML;
428+
429+
$movies = simplexml_load_string($data);
430+
431+
// Namespace http://www.w3.org/XML/1998/namespace is available as "xml".
432+
echo $movies->movie->attributes("xml", true)["id"] . "\n";
433+
434+
// Namespaced attributes can be accessed with attributes().
435+
echo $movies->movie->attributes("a", true)["link"] . "\n";
436+
437+
// Using namespace URI allows document to use any namespace alias.
438+
echo $movies->movie->attributes("http://a")["link"] . "\n";
439+
440+
// Children can be accessed with children().
441+
echo $movies->movie->children("http://a")->actor . "\n";
442+
443+
// Using xpath() with namespace requires registering it first.
444+
$movies->registerXPathNamespace("a", "http://a");
445+
echo count($movies->xpath("//a:actor")) . "\n";
446+
447+
// Even the default namespace must be registered.
448+
$movies->registerXPathNamespace("default", "http://default");
449+
echo count($movies->xpath("//default:movie")) . "\n";
450+
451+
// This is empty.
452+
echo count($movies->xpath("//movie")) . "\n";
453+
?>
454+
]]>
455+
</programlisting>
456+
</example>
457+
</para>
415458
</section>
416459

417460
<section xml:id="simplexml.examples-errors">

0 commit comments

Comments
 (0)