質問

I am trying to assign the <all> / <avg> value in this XML code to a variable, so that I can use it for calculations. But when I do this, and try to print the value, I get a blank screen. Can someone please help?

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

The php code I am using is as follows:

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

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

echo $unit_value;
役に立ちましたか?

解決

xpath returns an array of SimpleXMLElement objects .. so you can do this :

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

Working example here

or if you are using PHP => 5.4 you can do this :

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

Working example here

他のヒント

Please refer documentation here, $xml->xpath should return you the array. The docs also shows an example of how to access text nodes. Below is an excerpt from the docs

<?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";
 }
?>

which produces output as

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

which is I suppose exactly what you need.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top