【问题标题】:Save output in an xml file [closed]将输出保存在 xml 文件中 [关闭]
【发布时间】: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");
?>

【问题讨论】:

标签: php xml


【解决方案1】:

您可以通过 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);
?>

【讨论】:

  • 如果 curl 无法访问怎么办? :)
  • 正确,Curl 应该被安装,但是,嘿,我们可以继续,继续,继续...如果没有安装 PHP,如果防火墙阻止了他的传出连接,... .
  • 您的解决方案在这种情况下也不起作用:P
  • 谢谢老兄..你很棒...
  • 欢迎接受解决方案。下一次,在发布之前先尝试寻找解决方案;)
【解决方案2】:

使用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 所以它不是世界可执行的。
【解决方案3】:

http://de2.php.net/manual/en/book.dom.php

$dom = new DOMDocument();
$dom->load('http://www.example.com');
$dom->save('filename.xml');

【讨论】:

    【解决方案4】:

    可以这样做:

    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);
    

    【讨论】:

    • 谢谢!!但出现无法打开文件的错误..
    • 因为你没有权限在当前目录写。
    猜你喜欢
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    相关资源
    最近更新 更多