【发布时间】:2013-05-30 11:45:43
【问题描述】:
如何将以下链接的网页内容保存到 xml 文件中?下面的代码对我不起作用。
<?php
$url = "https://services.boatwizard.com/bridge/events/ae0324ff-e1a5-4a77-9783-f41248bfa975/boats?status=on";
copy($url, "file.xml");
?>
【问题讨论】:
如何将以下链接的网页内容保存到 xml 文件中?下面的代码对我不起作用。
<?php
$url = "https://services.boatwizard.com/bridge/events/ae0324ff-e1a5-4a77-9783-f41248bfa975/boats?status=on";
copy($url, "file.xml");
?>
【问题讨论】:
您可以通过 Curl 将给定链接的内容下载到 file.xml:
<?php
$url = 'https://services.boatwizard.com/bridge/events/ae0324ff-e1a5-4a77-9783-f41248bfa975/boats?status=on';
$fp = fopen (dirname(__FILE__) . '/file.xml', 'w+');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
【讨论】:
使用file_get_contents()和file_put_contents()两个函数;
file_get_contents - 获取文件的内容,如果启用了 fopen 包装器,则可以使用 URL 作为文件名。
file_put_contents - 将第二个参数的内容放到第一个参数指定的文件中
<?php
$url = "https://services.boatwizard.com/bridge/events/ae0324ff-e1a5-4a77-9783-f41248bfa975/boats?status=on";
file_put_contents('file.xml',file_get_contents($url));
@chmod('file.xml', 0755);
?>
【讨论】:
chmodfile.xml 所以它不是世界可执行的。
http://de2.php.net/manual/en/book.dom.php
$dom = new DOMDocument();
$dom->load('http://www.example.com');
$dom->save('filename.xml');
【讨论】:
可以这样做:
function savefile($filename,$data){
$fh = fopen($filename, 'w') or die("can't open file");
fwrite($fh, $data);
fclose($fh);
}
$data = file_get_contents('your link');
savefile('file.xml',$data);
【讨论】: