XML PHP #text problem

They have: 18 posts

Joined: Mar 2006

Hello again

Could anyone tell me why I get the following results?

The root element is British_Birds.
There are 1 child elements.
They are:
#text
resident
#text
rarevisitors
#text
-------------------
There should be 2 child elements and why is there #text in the results? I tried looking for answers but search engines won't accept a # in the query.

Thanks

Don
code:-

<?php
   
$XMLDoc
= DOMDocument::load('birds5.xml');

$root = $XMLDoc->documentElement;
echo(
"The root element is " . $root->nodeName . ".<br />");

$children $root->childNodes;

echo(
"There are " . count($children) . " child elements. <br />");
echo(
"They are: <br />");

for (
$child = $root->firstChild;
      
$child;
      
$child $child->nextSibling){

    echo
$child->nodeName;
    echo
"<br />";

   }
?>

birds5.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

Golden oriole
Oriolus oriolus
Summer
9-42
85
siskin.jpg
www.rspb.org.uk/birds/guide/s/siskin/index.asp

Hawk Owl
Accipiter nisus
rarevisitor
0
0
hawkowl.jpg
www.rspb.org.uk/birds/guide/h/hawkowl/index.asp

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

<?php
$children
= $root->childNodes;
?>

The above returns a DOMNodeList object, not an array. Hence change the subsequent call to count() to:
<?php
echo(\"There are \" . $children->length . \" child elements. <br />\");
?>

Note that this counts recursively, so you will get a result of 5 rather than 2. This is because DOM functions respect whitespace, and in between each element you have newlines and possibly indentation. To solve this, you have to tell DOMDocument not to preserve whitespace when it loads birds5.xml, like so:

<?php
$XMLDoc
= new DOMDocument;
$XMLDoc->preserveWhiteSpace = false;
$XMLDoc->load('birds5.xml');
?>

Smiling

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.