在php中打印特定的xml节点值

时间:2013-03-05 17:22:35

标签: php xml

我有以下XML文件

    <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>

并且,我正在使用以下PHP代码来打印“scenario_2”的孩子的名字和值

$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;

它完美地打印属性但不是VALUE。我该如何解决它,所以它也打印节点的VALUE?

2 个答案:

答案 0 :(得分:1)

你非常接近,但是对于SimpleXML,没有->nodeValue属性,只需将元素对象强制转换为字符串就可以了:

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

但我真的很想知道是谁创建了这样的XML,编号元素名称似乎相当适得其反。应该修复XML以便更好地使用。

答案 1 :(得分:0)

每个SimpleXMLElement都有一个属性innerNode。将其转换为字符串,它将是您正在寻找的值。