在本地机器上下载一个xml文件而不保存它php

问题描述

我正在尝试构建一个 PHP 脚本,该脚本从数据库下载带有数据的 xml 文件,问题是尝试将其保存在网络服务器中,然后下载它不起作用,因为我没有权限“无法打开流:HTTP 请求失败!HTTP/1.0 403 Forbidden” 我想知道是否可以构建 xml 文件并强制下载而不将其保存在 Web 服务器上。 环顾四周并尝试了不同的方法,但没有出现积极的输出 我是这种东西的新手(从 PHP 页面下载文件),尝试使用 readfile() 但它只是在页面显示 xml 内容 我正在使用 PHP,但 js ajax 或 html 也很好

代码

$results = MysqLi_query($conn,"SELECT * FROM testdb");
 $xml = new DomDocument("1.0","UTF-8");

$content = $xml->createElement("content");
$content = $xml->appendChild($content);

foreach($results as $result) {
    $item = $xml->createElement("item");

    $title = $xml->createElement("id",htmlspecialchars($result['num_id']));
    $title = $item->appendChild($title);

    $description = $xml->createElement("uid",htmlspecialchars($result['uid']));
    $description = $item->appendChild($description);

    $item = $content->appendChild($item);

}

$xml->FormatOutput = true;
$output = $xml->saveXML();
$xml->save("file.xml");

/*$xml = file_get_contents("http://mysite.altervista.org/test_download/file.xml");
file_put_contents("http://mysite.altervista.org/test_download/file.xml",$xml); // Now your xml file is saved.
*/
$file_url = "http://mysite.altervista.org/test_download/file.xml";
header("Content-Type: application/octet-stream");
header("Content-transfer-encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url);  
'''

解决方法

找到了一种明显避免来自altervista的权限锁的方法,只需要使用html(不认为这是一个很好的方法,但它有效)

<a href='http://mysite.altervista.org/test_download/file.xml' download>download</a>