PHP - 使用 ajax 提交表单,并返回 XML

标签 php ajax xml domdocument

我在使用 jQuery/AJAX 提交表单并返回成功消息 + XML 文件(用 PHP 生成)时遇到问题。

这是我现在拥有的:

invoice.php:

<form method="post" id="invoiceform">
<? /* Populate the form with input later on. For now, the XML data is hardcoded in PHP */ ?>
<button type="submit">Submit form</button>
</form>


//Submit the form:
$('#invoiceform').on('submit', function(e) { //use on if jQuery 1.7+
    e.preventDefault();  //prevent form from submitting
    e.stopImmediatePropagation(); //prevent double.

    //Show the loading message.
    $form = $(this);

     // Use Ajax to submit form data
        $.ajax({
            url: '/api/invoice/invoice_converter',
            type: 'POST',
            data: $form.serialize(),
            dataType: "json",
            success: function(data) {

                            console.log(data);

                if (data.result == 'success') {
                //Success
                $(".status").html(data.message);

            } else {
                $(".status").html(data.message);
           }
        },
        error: function(data) {
            console.log("Something went wrong!");
            console.log(data);

        }
    });

return false;

});

好的,上面只是将表单提交到下面的页面

invoice_converter.php:

$invoice = new Invoice;
if($_POST)
{
    $convertInvoice = $invoice->convertInvoice();

    if($convertInvoice == 1){
              $error = "Error: Error message goes here.";
              $stop = true;
    }
    if($stop){
        $result = array("result" => "error","message" => $error);
    }else{

        $result = array("result" => "success","message" => $convertInvoice);

    }

}
header('Content-type: application/json');
echo json_encode($result);

因此,上面的页面处理返回消息。实际的 XML 生成函数位于页面下方

functions.php:

function convertInvoice(){

    /* create a dom document with encoding utf8 */
      $domtree = new DOMDocument('1.0', 'UTF-8');

      /* create the root element of the xml tree */
      $xmlRoot = $domtree->createElement("xml");
      /* append it to the document created */
      $xmlRoot = $domtree->appendChild($xmlRoot);

      $currentTrack = $domtree->createElement("track");
      $currentTrack = $xmlRoot->appendChild($currentTrack);

      /* you should enclose the following two lines in a cicle */
      $currentTrack->appendChild($domtree->createElement('charge','letter'));
      $currentTrack->appendChild($domtree->createElement('description','Payable cover letters'));

      $currentTrack->appendChild($domtree->createElement('charge','vat'));
      $currentTrack->appendChild($domtree->createElement('description','Payable VAT'));

      /* get the xml printed */
      $xml =  $domtree->saveXML();

      return $xml;
}

console.log中上面返回的数据是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
  <track>
    <charge>letter</ charge >
    <description>Payable cover letters</ description >
    <charge>vat</ charge >
    <description>Payable VAT</ description >
   </track>
</xml>

这是正确的,但是,我希望能够将上述内容“保存”到 XML 文件中,并使其可供用户下载。

最佳答案

您需要制作一个可写文件并将$xml写入文件。
此代码创建 track.xml 并将下载链接插入文档。

使用fopen 以写入(如果不存在则创建)模式打开文件,然后使用fwrite 将内容写入文件,然后使用fclose 关闭文件。该文件必须放在公共(public)目录中,以确保网络服务器可以访问它。

// Open file and write contents
$file = fopen('track.xml', 'w+');
fwrite($file, $xml);
fclose($file);

// Generate download link
echo '<a href="/path/to/track.xml" download>Download</a>';

注意:您需要确保输出目录可由 PHP 使用:

chown www-data:www-data /var/www/path/to/output
chmod 775 /var/www/path/to/output

关于PHP - 使用 ajax 提交表单,并返回 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45208713/

相关文章:

xml - 如何使用xpath在xml中查找数字数据类型信息

通过 AJAX 的 jQuery XML : missing some nodes occasionally

php - SQL使空变量全选

javascript - 将数据返回到 jquery 中的 ajax 调用

ajax - 如何在不重新加载页面的情况下将任意 JSON 发送到 node.js?

ajax - 我如何使用 <p :fileUpload> with mode simple and ajax ="true"?

xml - 使用 Wix 在安装程序中插入版权/注册符号

php - 不使用子域重定向移动设备

php - 优化大型且逐渐增加的数据库

PHP:立即返回响应,但在后台运行多个冗长的 shell_exec 函数