getting xml from URL into variable

mhopkins321 picture mhopkins321 · Dec 31, 2012 · Viewed 30.4k times · Source

I am trying to get an xml feed from a url

http://api.eve-central.com/api/marketstat?typeid=1230&regionlimit=10000002

but seem to be failing miserably. I have tried

Yet none of these seem to echo a nice XML feed when I either echo or print_r. The end goal is to eventually parse this data but getting it into a variable would sure be a nice start.

I have attached my code below. This is contained within a loop and $typeID does in fact give the correct ID as seen above

$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'&regionlimit=10000002';
echo $url."<br />";
$xml = new SimpleXMLElement($url);
print_r($xml);

I should state that the other strange thing I am seeing is that when I echo $url, i get

http://api.eve-central.com/api/marketstat?typeid=1230®ionlimit=10000002

the &reg is the registered trademark symbol. I am unsure if this is "feature" in my browser, or a "feature" in my code

Answer

Nir Alfasi picture Nir Alfasi · Dec 31, 2012

Try the following:

<?php
$typeID = 1230;
// set feed URL
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'&regionlimit=10000002';
echo $url."<br />";
// read feed into SimpleXML object
$sxml = simplexml_load_file($url);

// then you can do
var_dump($sxml);

// And now you'll be able to call `$sxml->marketstat->type->buy->volume` as well as other properties.
echo $sxml->marketstat->type->buy->volume;

// And if you want to fetch multiple IDs:
foreach($sxml->marketstat->type as $type){
    echo $type->buy->volume . "<br>";
}
?>