0

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;

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Manse, this worked perfectly, thanks! Is there a way to assign the [0] to $unit_value all in once line? Something like the following maybe? $unit_value = $xml->xpath("//stats//type[@id='a']//buy//avg")[0];
@user1452060 only from PHP 5.4 onwards -> php.net/manual/en/language.types.array.php#example-87 - I have updated my answer with an example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.