Programmer
Programmer

Reputation: 1

print specific xml node value in php

I have the following XML file

    <study>
   <participant name="Jone" gender="male" nationality="Canadian" job="web developer" country="Canada" years="2"/>
   <scenario_1>
      <s1_first name="drieseng">Scenario 1 first developer</s1_first>
      <s1_second name="Scott Hernandez">Scenario 1 2nd developer</s1_second>
      <s1_third name="Ryan Boggs">Scenario 1 3rd developer</s1_third>
      <s1_forth name="Ian MacLean">Scenario 1 4th developer</s1_forth>
      <s1_fifth name="Michael C. Two">Scenario 1 5th developer</s1_fifth>
   </scenario_1>
   <scenario_2>
      <s2_first name="Charles Chan">Scenario 2 1st developer</s2_first>
      <s2_second name="Charles Chan">Scenario 2 2nd developer</s2_second>
      <s2_third name="drieseng">Scenario 2 3rd developer</s2_third>
      <s2_forth name="claytonharbour">Scenario 2 4th developer</s2_forth>
      <s2_fifth name="Hala Dajani">Scenario 2 4th developer</s2_fifth>
   </scenario_2>
   <scenario_3>
      <s3_first name="Michael C. Two">Scenario 3 1st developer</s3_first>
      <s3_second name="Giuseppe Greco">Scenario 3 2nd developer</s3_second>
      <s3_third name="Ian MacLean">Scenario 3 3rd developer</s3_third>
      <s3_forth name="Gregory Goltsov">Scenario 3 4th developer</s3_forth>
      <s3_fifth name="Michael C. Two">Scenario 3 5th developer</s3_fifth>
   </scenario_3>
</study>

And, I'm using the following PHP code to print names and values of "scenario_2"'s children

$xml_temp = simplexml_load_file("db/temp.xml");

$scenarios = $xml_temp -> children();

foreach( $scenarios[2] -> children() as $scenario_2_developer){

   echo $scenario_2_developer['name']. ": " .  $scenario_2_developer -> nodeValue;

It prints the attributes perfectly BUT NOT the VALUE. How can I fix it, so it prints the VALUE of the node as well?

Upvotes: 0

Views: 535

Answers (2)

hakre
hakre

Reputation: 197624

You are pretty close, however with SimpleXML there is not ->nodeValue property, just cast the element object to string and you're fine:

echo $scenario_2_developer['name'], ": ", $scenario_2_developer, "\n";
                                                   ^
                                                   |
                                   echo casts this object to string

But I really wonder who creates such an XML, numbering element names that way seems pretty counter-productive. The XML should be fixed for better use.

Upvotes: 1

cwallenpoole
cwallenpoole

Reputation: 81988

Every SimpleXMLElement has a property innerNode. Cast that to a string and it will be the value you're looking for.

Upvotes: 0

Related Questions