开发者

Write Post data to file with PHP

I need to post data using the code below, to php file that will save it in a text file. I just don't know how to create the php file to receive the data below and save it in a text file. as simple as possible.

try {  
    // Add your data  
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
    nameValuePairs.add(new BasicNameValuePair("stringData", "12345"));  
    nameValuePairs.add(new BasicNameValuePair("stringData", "AndDev is Cool!"));  
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

    // Execute HTTP Post Request  
    HttpResponse response = httpclient.execute(httppost);  
  开发者_如何学Python  String responseText = EntityUtils.toString(response.getEntity()); 
    tv.setText(responseText);             
} catch (ClientProtocolException e) {  
    // TODO Auto-generated catch block  
} catch (IOException e) {  
    // TODO Auto-generated catch block  
}  


Simple as:

file_put_contents('test.txt', file_get_contents('php://input'));


1) In PHP, to get POST data from an incoming request use the $_POST array. The POST array in PHP is associative, which means that each incoming parameter will be a key-value pair. In development it's helpful to understand what you're actually getting in $_POST. You can dump the contents using printf() or var_dump() like the following.

var_dump($_POST);

-- or --

printf($_POST);

2) Choose a useful string-based format for storing the data. PHP has a serialize() function, which you could use to turn the array into a string. It's also easy to turn the array into a JSON string. I suggest using JSON since it's natural to use this notation across various languages (whereas using a PHP serialization would somewhat bind you to using PHP in the future). In PHP 5.2.0 and above the json_encode() function is built-in.

$json_string = json_encode($_POST);

// For info re: JSON in PHP:
// http://php.net/manual/en/function.json-encode.php

3) Store the string in a file. Try using fopen(), fwrite(), and fclose() to write the json string to a file.

$json_string = json_encode($_POST);

$file_handle = fopen('my_filename.json', 'w');
fwrite($file_handle, $json_string);
fclose($file_handle);

// For info re: writing files in PHP:
// http://php.net/manual/en/function.fwrite.php

You'll want to come up with a specific location and methodology to the file paths and file names used.

Note: There's also the possibility of getting the HTTP request's POST body directly using $HTTP_RAW_POST_DATA. The raw data will be URL-encoded and it will be a string that you can write to a file as described above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜