救命!通过php simplexml获取节点值!

时间:2010-11-19 06:27:38

标签: php simplexml

我只想从xml节点获取值。所以我按照php文档中的代码: SimpleXMLElement :: xpath()。但它没有。我认为Xpath更加不方便,是否有更好的方法来获取我想要的节点?!

我的PHP代码:

<?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);
?>

它返回:

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

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

非常感谢!!

1 个答案:

答案 0 :(得分:3)

用以下内容替换整个循环:

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

甚至:

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