我是否使用 fopen 或 curl 来加载 PHP 中给定 URL 的 XML 文件
我有一个可以通过 URL 获取的 XML 文件。我知道我可以使用 fopen
获取文件,但有时我看到脚本使用 curl
。使用 curl
比使用 fopen
获取 XML 文件有优势吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
allow_url_fopen
,如果你想用fopen
打开远程文件是必需的,可以禁用;因此,在某些情况下fopen('http://...')
是不可能的。注意:在这个答案中,我说“
fopen
”,但它与所有可以访问远程文件的 PHP 函数完全相同:fopen
、file_get_contents
,simplexml_load_file
, ...另一方面,curl 是一个扩展,并不总是启用。
One nice with curl is that it's pretty easy to configure, and there are a lot of existing options *(see [`curl_setopt`][3])*
要配置
fopen
访问远程文件的方式,有点棘手——您通常必须使用流(请参阅此处,例如) ;而且,一般来说,了解curl的人比掌握stream的开发人员还要多。Safest way -- especially if your application will be deployed to servers on which you are not administrator, and cannot re-configure :
allow_url_fopen
, which is required if you want to open a remote file withfopen
, can be disabled ; so, there are situations in whichfopen('http://...')
is not possible.Note : in this answer, I say "
fopen
", but it's exactly the same with all PHP functions that can access remote files :fopen
,file_get_contents
,simplexml_load_file
, ...On the other hand, curl is an extension, and is not always enabled either.
One nice with curl is that it's pretty easy to configure, and there are a lot of existing options *(see [`curl_setopt`][3])*
To configure the way
fopen
accesses remote files, it's a bit trickier -- you'll generally have to work with streams (see here, for example) ; and, generally speaking, there are more people knowing curl than there are developpers mastering streams.Safest way -- especially if your application will be deployed to servers on which you are not administrator, and cannot re-configure :
好吧,如果您要使用 SimpleXML 加载文件,您可以使用
但是,某些服务器会限制从此功能加载 url。在这种情况下,您将被限制使用 cURL。
Well, if you are going to use SimpleXML to load the file you can use
However, some servers will restrict loading urls from this function. In this case you would be restricted to cURL.
fopen 使用起来更简单,而且我认为并非所有服务器设置都支持开箱即用的 curl。如果 fopen 适合您,那么它可能是您的最佳选择。
fopen is simpler to use, and I think not all server setups support curl out of the box. If fopen works fine for you it's probably your best choice.