我有这个参数来下载XML文件:
wget --http-user=user --http-password=pass http://www.example.com/file.xml
Run Code Online (Sandbox Code Playgroud)
我如何在php中使用它来打开这个xml文件?
Mat*_*ark 48
wget的
wget
是一个linux命令,而不是PHP命令,所以要运行它你需要使用exec
,这是一个用于执行shell命令的PHP命令.
exec("wget --http-user=[user] --http-password=[pass] http://www.example.com/file.xml");
Run Code Online (Sandbox Code Playgroud)
如果您正在下载一个大文件,并且想要监视进度,这可能很有用,但是当您处理对内容感兴趣的页面时,有一些简单的功能可以做到这一点.
该exec
功能默认启用,但在某些情况下可能会被禁用.此配置选项驻留在您的php.ini
,启用,exec
从disabled_functions
配置字符串中删除.
替代
使用file_get_contents
我们可以检索指定的URL/URI的内容.当您只需要将文件读入变量时,这将是用作curl替代品的完美函数 - 在构建URL时遵循URI语法.
// standard url
$content = file_get_contents("http://www.example.com/file.xml");
// or with basic auth
$content = file_get_contents("http://user:pass@www.example.com/file.xml");
Run Code Online (Sandbox Code Playgroud)
如上所述Sean the Bean
- 您可能还需要 在php.ini中更改为允许在此方法中使用URL,但是,默认情况下应该为true.allow_url_fopen
true
如果你想在本地存储该文件,有一个函数file_put_contents
可以将其写入文件,结合之前的文件,这可以模拟文件下载:
file_put_contents("local_file.xml", $content);
Run Code Online (Sandbox Code Playgroud)
Ja͢*_*͢ck 33
如果目的是仅加载应用程序内的内容,您甚至不需要使用wget
:
$xmlData = file_get_contents('http://user:pass@example.com/file.xml');
Run Code Online (Sandbox Code Playgroud)
请注意,如果allow_url_fopen
在php.ini或Web服务器配置(例如httpd.conf)中禁用(默认情况下已启用),则此功能将不起作用.
如果您的主机明确禁用它或者您正在编写库,则建议使用cURL或抽象功能的库,例如Guzzle.
use GuzzleHttp\Client;
$client = new Client([
'base_url' => 'http://example.com',
'defaults' => [
'auth' => ['user', 'pass'],
]]);
$xmlData = $client->get('/file.xml');
Run Code Online (Sandbox Code Playgroud)
Ada*_*dam 10
您可以使用curl
以获取数据并进行标识(对于"基本"和"摘要"身份验证),而无需扩展权限(如exec或allow_url_fopen).
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/file.xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
$result = curl_exec($ch);
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)
然后,您的结果将存储在$result
变量中.
归档时间: |
|
查看次数: |
132827 次 |
最近记录: |