使用file_get_contents()加载远程xml页面

Log*_*man 12 php xml file-get-contents

我在互联网上看到了类似的一些问题,没有答案.

我想将远程XML页面的源返回到字符串中.出于此问题的目的,远程XML页面是:

http://www.test.com/foo.xml
Run Code Online (Sandbox Code Playgroud)

在常规的Web浏览器中,我可以查看页面,源代码是XML文档.file_get_contents('http://www.test.com/foo.xml')但是,当我使用它时,它返回一个带有相应URL的字符串.

是否可以检索XML组件?我不在乎它是否使用file_get_contents,只是一些可行的东西.

Seb*_*Seb 15

您需要在服务器中设置allow_url_fopen才能使其正常工作.

如果你没有,那么你可以使用这个功能作为替代品:

<?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;
    }
?>
Run Code Online (Sandbox Code Playgroud)

借来自这里.


Bjö*_*örn 14

这看起来很奇怪.file_get_contents()是否返回其他站点的有效数据(不仅仅是XML)?如果已启用fopen-wrappers(默认情况下,它们),则URL只能用作filename参数.

我猜你以后要处理检索到的XML - 那么你应该可以使用simplexml_load _file()直接将它加载到SimpleXml中.

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

我建议使用SimpleXML来读取XML文件,它非常易于使用.