php 从 URL 获取 xml 到变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14105922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting xml from URL into variable
提问by mhopkins321
I am trying to get an xml feed from a url
我正在尝试从 url 获取 xml 提要
http://api.eve-central.com/api/marketstat?typeid=1230®ionlimit=10000002
but seem to be failing miserably. I have tried
但似乎失败得很惨。我试过了
http_get
http_get
Yet none of these seem to echo a nice XML feed when I either echoor print_r. The end goal is to eventually parse this data but getting it into a variable would sure be a nice start.
然而,当我echo或print_r. 最终目标是最终解析这些数据,但将其放入变量肯定是一个不错的开始。
I have attached my code below. This is contained within a loop and $typeIDdoes in fact give the correct ID as seen above
我在下面附上了我的代码。这包含在一个循环$typeID中,实际上确实给出了正确的 ID,如上所示
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'®ionlimit=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
我应该说我看到的另一个奇怪的事情是当我回显 $url 时,我得到
http://api.eve-central.com/api/marketstat?typeid=1230?ionlimit=10000002
the ®is the registered trademark symbol. I am unsure if this is "feature" in my browser, or a "feature" in my code
该®是注册商标符号。我不确定这是浏览器中的“功能”还是代码中的“功能”
回答by alfasin
Try the following:
请尝试以下操作:
<?php
$typeID = 1230;
// set feed URL
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'®ionlimit=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>";
}
?>
回答by Supericy
You need to fetch the data from the URL in order to make an XML object.
您需要从 URL 获取数据以创建 XML 对象。
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'®ionlimit=10000002';
$xml = new SimpleXMLElement(file_get_contents($url));
// pre tags to format nicely
echo '<pre>';
print_r($xml);
echo '</pre>';

