13

I'm looking for a PHP script that can accept an XML file via a POST, then send a response....

Does anyone have any code that could do this?

So far the only code I have is this but not sure about the response or if indeed I am even going in the right direction as XML characters are not saved correctly. Any ideas?

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

?>

My files are all empty...the contents is not being written to them. They are being created.

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

I'm not talking about uploading a file. Someone wants to send an XML file on a regular basis through a HTTP connection.

I just need a script running on my server to accept their post to my URL and then save the file to my server and send them a response back saying acknowledged or accepted.

1
  • Your "response" is anything you would "echo" or output during the execution of your script. Commented Jun 2, 2009 at 14:18

1 Answer 1

6

Your method is fine, and by the looks of it, the proper way to do it, with some notes:

  • 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.