通过PHP的POST方法接收XML文件

13
我正在寻找一个能够通过POST接收XML文件并发送响应的PHP脚本。是否有人有相关代码可以提供?
目前我仅有的代码如下,但不确定响应是否正确,或者我是否朝着正确的方向前进,因为XML字符未被正确保存。有什么想法吗?
<?php

if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){ 
    $postText = file_get_contents('php://input'); 
}

$datetime=date('ymdHis'); 
$xmlfile = "myfile" . $datetime . ".xml"; 
$FileHandle = fopen($xmlfile, 'w') or die("can't open file"); 
fwrite($FileHandle, $postText); 
fclose($FileHandle);

?>

我的文件全都是空的...内容没有被写入。它们只是被创建了。

//source html
<form action="quicktest.php" method="post" mimetype="text/xml" enctype="text/xml" name="form1">
<input type="file" name="xmlfile">
<br>

<input type="submit" name="Submit" value="Submit">

</form>

//destination php

$file = $_POST['FILES']['xmlfile'];

$fileContents= file_get_contents($file['tmp_name']);

$datetime=date('ymdHis'); 
$xmlfile="myfile" . $datetime . ".xml"; 
$FileHandle=fopen($xmlfile, 'w') or die("can't open file"); 

fwrite($FileHandle, $postText); 
fclose($FileHandle);

我不是在讨论上传文件。有人想要通过HTTP连接定期发送一个XML文件。

我只需要在我的服务器上运行一个脚本来接受他们对我的URL的POST请求,然后将文件保存到我的服务器并向他们发送一个响应,表示已确认或已接受。


你的“response”是在脚本执行过程中输出或回显的任何内容。 - anonymous coward
1个回答

6

您的方法很好,看起来是正确的做法,这里有一些注意事项:

  • If you have PHP5, you can use file_put_contents as the inverse operation of file_get_contents, and avoid the whole fopen/fwrite/fclose. However:
  • If the XML POST bodies you will be accepting may be large, your code right now may run into trouble. It first loads the entire body into memory, then writes it out as one big chunk. That is fine for small posts but if the filesizes tend into megabytes it would be better do to it entirely with fopen/fread/fwrite/fclose, so your memory usage will never exceed for example 8KB:

    $inp = fopen("php://input");
    $outp = fopen("xmlfile" . date("YmdHis") . ".xml", "w");
    
    while (!feof($inp)) {
        $buffer = fread($inp, 8192);
        fwrite($outp, $buffer);
    }
    
    fclose($inp);
    fclose($outp);
    
  • Your filename generation method may run into name collissions when files are posted more regularly than 1 per second (for example when they are posted from multiple sources). But I suspect this is just example code and you are already aware of that.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接