qinHaiXiang
qinHaiXiang

Reputation: 6419

Help! get node value via php simplexml !

I just want to get the value from xml node.So I following the code from php document: SimpleXMLElement::xpath() .But it didn't.And I thought the Xpath is much more inconvenience ,is there a much better way to get the node I want??!

my php code:

<?php

/**
 * @author kevien
 * @copyright 2010
 */

$arr = array ();

$xml = simplexml_load_file("users.xml");

$result = $xml->xpath('/users/user[@id="126"]/watchHistory/whMonthRecords[@month="2010-09"]/whDateList/date');

while(list( , $node) = each($result)) {

    array_push($arr, $node);
}

print_r($arr);
?>

it returns:

Array ( [0] => SimpleXMLElement Object ( [0] => 02 ) [1] => SimpleXMLElement Object ( [0] => 03 ) [2] => SimpleXMLElement Object ( [0] => 06 ) [3] => SimpleXMLElement Object ( [0] => 10 ) [4] => SimpleXMLElement Object ( [0] => 21 ) ) 

my part of users.xml :

<users>
    <user id="126">
        <name>老黄牛三</name>
        <watchHistory>
            <whMonthRecords month="2010-09">
                <whDateList month="2010-09">
                    <date>02</date>
                    <date>03</date>
                    <date>06</date>
                    <date>10</date>
                    <date>21</date>
                </whDateList>
                      </<whMonthRecords>
               </<watchHistory>>
      </user>
  </users>

Thank you very much!!

Upvotes: 0

Views: 3320

Answers (1)

zerkms
zerkms

Reputation: 254886

Replace your whole loop with:

foreach ($result as $node) {
    $arr[] = (string)$node;
}

or even:

$result = array_map('strval', $result);

Upvotes: 3

Related Questions