Reputation: 15345
I have a page on a remote server that returns a single xml value
<?xml version="1.0" ?><Tracker>12345</Tracker>
How do I go about getting the value 12345 or whatever is in the tag into a PHP variable? I know I can't do something as simple as:
<?php
$var = http://www.www.com/file.php;
echo $var; //12345
?>
I'm new to the entire idea of creating a web service - I think that's what this should be.?.
Upvotes: 2
Views: 3061
Reputation: 401062
You have to go in two steps :
simplexml_load_string
for instanceNote that those two steps can be merged as one, using simplexml_load_file
, if the configuration of your server allows you to do that.
Once you have that XML in a PHP variable, using SimpleXML, it's quite easy to get the value you want. For instance :
$string = '<?xml version="1.0" ?><Tracker>12345</Tracker>';
$xml = simplexml_load_string($string);
echo (string)$xml;
Will get you
12345
And getting the content of that XML from the remote URL can be as simple as :
$string = file_get_contents('http://your-remote-url');
And if you can do that, you can also use that remote URL directly with SimpleXML :
$xml = simplexml_load_file('http://your-remote-url');
echo (string)$xml;
But this will only work if allow_url_fopen
is enabled in your server's configuration.
If allow_url_fopen
is disabled on your server, you can get the XML from the remote server using curl ; something like this should do the trick, for instance :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://your-remote-url");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$string = curl_exec($ch);
curl_close($ch);
And, then, you can still use simplexml_load_string
, as I did in my first example.
(If using curl, take a look at the documentation of curl_setopt
: there are several options that might interest your -- for instance, to specify timeouts)
Upvotes: 5
Reputation: 113350
$xml = simplexml_load_file('test.xml');
$var = $xml[0];
Upvotes: 0
Reputation: 3625
I don't know PHP that good, but:
Upvotes: 0