将XML nodeValue拉入php变量

时间:2012-07-13 14:47:05

标签: php xml xpath nodevalue

我正在尝试将此XML代码中的<all> / <avg>值分配给变量,以便我可以将其用于计算。但是当我这样做,并尝试打印该值时,我得到一个空白屏幕。有人可以帮忙吗?

<stats>
    <type id="a">
        <buy>
            <volume>698299009</volume>
            <avg>17.94</avg>
            <max>18.45</max>
            <min>1.00</min>     
        </buy>
        <sell>
            <volume>16375234</volume>
            <avg>21.03</avg>
            <max>24.99</max>
            <min>20.78</min>        
        </sell>
        <all>
            <volume>714674243</volume>
            <avg>18.01</avg>
            <max>24.99</max>
            <min>1.00</min>     
        </all>
    </type>
</stats>

我使用的php代码如下:

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

$unit_value = $xml->xpath("/stats/type[@id='a']/buy/avg/")->nodeValue;

echo $unit_value;

2 个答案:

答案 0 :(得分:2)

请参阅文档here$xml->xpath应该返回数组。文档还显示了如何访问文本节点的示例。以下是文档的摘录

<?php
  $string = <<<XML
   <a>
     <b>
       <c>text</c>
       <c>stuff</c>
     </b>
     <d>
       <c>code</c>
     </d>
  </a>
 XML;

 $xml = new SimpleXMLElement($string);

 /* Search for <a><b><c> */
 $result = $xml->xpath('/a/b/c');

 while(list( , $node) = each($result)) {
   echo '/a/b/c: ',$node,"\n";
 }

 /* Relative paths also work... */
 $result = $xml->xpath('b/c');

 while(list( , $node) = each($result)) {
   echo 'b/c: ',$node,"\n";
 }
?>

产生输出

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

我想你正是​​需要的。

答案 1 :(得分:1)

xpath返回一个SimpleXMLElement对象数组..所以你可以这样做:

$unit_value = $xml->xpath("//stats//type[@id='a']//buy//avg");
echo (string)$unit_value[0]; // cast to string not required

Working example here

或者如果您使用PHP =&gt; 5.4你可以这样做:

$unit_value = $xml->xpath("//stats//type[@id='a']//buy//avg")[0];
echo $unit_value; 

Working example here

相关问题