2010-12-17 48 views
2

我无法使用simplexml_load_file函数从文件获取XML。我曾尝试使用Google,但其他人似乎在遇到实际错误或警告时遇到问题。我没有得到任何错误,没有警告,但是当我这样做:PHP - 使用simplexml_load_file获取XML的问题

$sims = simplexml_load_file("http://my-url.com/xml.php") or die("Unable to load XML file!"); 
var_dump($sims); 

输出为:

object(SimpleXMLElement)#1 (1) { 
    [0]=> 
    string(1) " 
" 
} 



但是,如果我这样做:

$ch = curl_init("http://my-url.com/xml.php"); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 
curl_close($ch); 
echo $output; 

输出是:

<?xml version="1.0"?> 
<simulators> 
    <simulator> 
     <mac>00-1A-4D-93-27-EC</mac> 
     <friendlyName>a Travis Desk</friendlyName> 
     <roundSessions>2</roundSessions> 
     <rangeSessions>0</rangeSessions> 
     <timePlayed>00:03:21</timePlayed> 
    </simulator> 
</simulators> 



我得到它做这个工作:

$ch = curl_init("http://my-url.com/xml.php"); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 
curl_close($ch); 

$sims = simplexml_load_string($output) or die("Unable to load XML file!"); 
var_dump($sims); 

,输出:

object(SimpleXMLElement)#1 (1) { 
    ["simulator"]=> 
    object(SimpleXMLElement)#2 (5) { 
    ["mac"]=> 
    string(17) "00-1A-4D-93-27-EC" 
    ["friendlyName"]=> 
    string(13) "a Travis Desk" 
    ["roundSessions"]=> 
    string(1) "2" 
    ["rangeSessions"]=> 
    string(1) "0" 
    ["timePlayed"]=> 
    string(8) "00:03:21" 
    } 
} 

我只是想知道为什么第一个方法不起作用?我有在Ubuntu Server 10.04上运行的PHP Version 5.3.2-1ubuntu4.5和libxml版本2.7.6。

谢谢!

-Travis

+0

可以确认URL仅仅是通过'http:// my-url.com/xml.php'没有任何'$ _GET'? – ajreal 2010-12-17 16:56:11

回答

-1

感谢您的快速反应。

@ajreal - 你是在正确的轨道上。原来,这是我自己在查询字符串中的一个愚蠢的错误,出于某种原因,它通过cURL或浏览器调用它时起作用,但通过simplexml_load_file无法工作。对不起浪费你的时间!

-Travis

1

我相信这可能是因为您的XML内容位于PHP扩展文件中。您需要将http标头设置为xml。

header ("Content-type: text/xml"); 

把这个xml输出到你的php脚本中,它是负责吐出xml的。 (一在 “http://my-url.com/xml.php”)

http://www.satya-weblog.com/2008/02/header-for-xml-content-in-php-file.html

+0

很好的建议,但事实证明它不是必需的。可能是一个好主意,但我认为simplexml_load_file函数只是将URL的输出作为一个字符串来使用,所以我认为在开始时就需要<?xml version =“1.0”?>“。不过谢谢你的回应! – Travesty3 2010-12-17 17:15:56

相关问题