通过php中的帖子接收xml文件

13 php xml post http

我正在寻找一个可以通过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);

?>
Run Code Online (Sandbox Code Playgroud)

我的文件都是空的......内容没有被写入.他们正在创建.

//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);
Run Code Online (Sandbox Code Playgroud)

我不是在谈论上传文件.有人想通过HTTP连接定期发送XML文件.

我只需要在我的服务器上运行一个脚本来接受他们的帖子到我的URL,然后将文件保存到我的服务器并向他们发送一个回复,说明已确认或已接受.

rix*_*rrr 6

你的方法很好,从它的外观来看,正确的方法,有一些注意事项:

  • 如果你有PHP5,你可以使用file_put_contents反向操作file_get_contents,并避免整体fopen/fwrite/fclose.然而:
  • 如果您接受的XML POST主体可能很大,那么您的代码现在可能会遇到麻烦.它首先将整个主体加载到内存中,然后将其作为一个大块写出来.对于小帖子来说这很好但是如果文件大小倾向于兆字节,那么最好完全使用它fopen/fread/fwrite/fclose,因此你的内存使用量永远不会超过例如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);
    
    Run Code Online (Sandbox Code Playgroud)
  • 当文件的发布频率高于每秒1次时(例如,从多个源发布文件时),您的文件名生成方法可能会遇到名称冲突.但我怀疑这只是示例代码,您已经意识到这一点.