views:

2424

answers:

2

I have seen some questions similar to this on the internet, none with an answer.

I want to return the source of a remote XML page into a string. The remote XML page, for the purposes of this question, is:

http://www.test.com/foo.xml

In a regular webbrowser, I can view the page and the source is an XML document. When I use file_get_contents('http://www.test.com/foo.xml'), however, it returns a string with the corresponding URL.

Is there to retrieve the XML component? I don't care if it uses file_get_contents or not, just something that will work.

+1  A: 

That seems odd. Does file_get_contents() return any valid data for other sites (not only XML)? An URL can only be used as the filename parameter if the fopen-wrappers has been enabled (which they are by default).

I'm guessing you're going to process the retrieved XML later on - then you should be able to load it into SimpleXml directly using the simplexml_load _file().

try {
   $xml = simplexml_load_file('http://www.test.com/foo.xml');
   print_r($xml);
} ...

I recommend using SimpleXML for reading XML-files, it's very easy to use.

Björn
+1  A: 

You need to have allow_fopen_url set in your server for this to work.

If you don´t, then you can use this function as a replacement:

<?php
function curl_get_file_contents($URL)
    {
        $c = curl_init();
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_URL, $URL);
        $contents = curl_exec($c);
        curl_close($c);

        if ($contents) return $contents;
            else return FALSE;
    }
?>

Borrowed from here.

Seb
It's not certain to be a replacement - these functions requires that PHP is compiled with cURL enabled. If the fopen-wrappers are disabled the cURL functionality is probably disabled as well. Better to use a fsockopen() function to be on the safe side.
Björn
I've come into lots of hostings having fopen-wrappers disabled but not cURL, so while it's true it's not exactly a replacement, it might be a nice workaround.
Seb