xpath node names

They have: 18 posts

Joined: Mar 2006

Hi

I'm experimenting with PHP/XML and XPath, I have some very simple code that returns the contents of nodes. What I cannot do is find the code that return the node names i.e British_Birds, species, name etc. I am using PHP 5.0.3 which supports xpath but I am getting a lot of undefined method errors. Does anyone know how I get the node names?

Code so far:-

<?php
$s
= simplexml_load_file('birds5.xml');

foreach (
$s->xpath('//species/name') as $species_name)
     {
       echo
$species_name, '<br />';
    }
?>

Returns:-
Golden oriole
Sparrowhawk
Siskin
Hoopoe

-------------------------------
birds5.xml

Golden oriole
Oriolus oriolus
Summer
9-42
85
golden_oriole.jpg
http://www.rspb.org.uk/birds/guide/g/goldenoriole/index.asp

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

I don't understand your question fully. When you say you want to "get the node names" - the node names of what?

Do you want to perform a reverse lookup using the values of nodes? You can select nodes using a variety of xpath queries. See here: http://www.w3schools.com/xpath/xpath_syntax.asp

If you want to get the field name from the results, try inspecting the SimpleXML object returned by the xpath function. You might be able to pull your data from there. But this seems redundant as you've already specified the field name in your argument to xpath.

If you really want to mangle with field names and the document tree, you'd best be using the DOM extension. You can import SimpleXML to DOM and use DOM's API to do what you want. You can also import back to SimpleXML if you'd like.

Does that help? 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.