开发者

PHP - problems getting XML using simplexml_load_file

开发者 https://www.devze.com 2023-01-31 07:16 出处:网络
I\'m having trouble getting the XML from a file using the simplexml_load_file function. I have tried googling, but everyone else seems to have problems when they get an actual error or warning. I get

I'm having trouble getting the XML from a file using the simplexml_load_file function. I have tried googling, but everyone else seems to have problems when they get an actual error or warning. I get no error and no warnings, but when I do this:

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

the output is:

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

However, if I do this:

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

the output is:

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

I have gotten it to work by doing this:

$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);

which outputs:

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

I'm just wondering why the first method didn't work? I have PHP Version 5.3.2-1ubuntu4.5 and libxml Version 2.7.6 running on Ubuntu Server 10.04.

Thanks!

-Travis


I believe it may be because your xml content is located within a .php extension file. You need to set the http header to xml.

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

Put that before the xml is outputted in your php script that is responsible for spitting out the xml. (the one at "http://my-url.com/xml.php")

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


Thanks for the quick responses.

@ajreal - you were on the right track. Turns out it was my own dumb mistake in the querystring that, for some reason, worked when calling it via cURL or in the browser, but didn't work via simplexml_load_file. Sorry for wasting your time!

-Travis

0

精彩评论

暂无评论...
验证码 换一张
取 消