php 使用 file_get_contents() 加载远程 xml 页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/695296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading a remote xml page with file_get_contents()
提问by Logan Serman
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:
我想将远程 XML 页面的源返回为字符串。就本问题而言,远程 XML 页面是:
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.
在常规的网络浏览器中,我可以查看页面并且源是一个 XML 文档。file_get_contents('http://www.test.com/foo.xml')但是,当我使用时,它会返回一个带有相应 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.
是否可以检索 XML 组件?我不在乎它是否使用 file_get_contents ,只是一些有用的东西。
回答by Seb
You need to have allow_url_fopen set in your server for this to work.
您需要在服务器中设置 allow_url_fopen 才能使其工作。
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.
从这里借来的。
回答by Bj?rn
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-wrappershas been enabled (which they are by default).
这似乎很奇怪。file_get_contents() 是否为其他站点(不仅是 XML)返回任何有效数据?如果fopen-wrappers已启用(默认情况下启用),则URL 只能用作文件名参数。
I'm guessing you're going to process the retrieved XML later on - then you should be able to load it into SimpleXmldirectly using the simplexml_load _file().
我猜您稍后将处理检索到的 XML - 然后您应该能够使用 simplexml_load _file() 将它直接加载到SimpleXml 中。
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.
我推荐使用 SimpleXML 来读取 XML 文件,它非常易于使用。

