Export data to file php

Save PHP variables to a text file

I was wondering how to save PHP variables to a txt file and then retrieve them again. Example: There is an input box, after submitted the stuff that was written in the input box will be saved to a text file. Later on the results need to be brought back as a variable. So lets say the variable is $text I need that to be saved to a text file and be able to retrieve it back again.

Actually, you can save variables, but not in a clean way. It’s always possible to compact() your variables in an array and later extract() them, though.

All the answers are answering your specific question, but Gordon is absolutely right: It really sounds like you want Sessions.

7 Answers 7

This should do what you want, but without more context I can’t tell for sure.

$text = "Anything"; $var_str = var_export($text, true); $var = ""; file_put_contents('filename.php', $var); 
include 'filename.php'; echo $text; 

thank you very much.You are a genius.Actually this is what I am looking for. Working perfectly.Thanks again dear friend

Note that returning value is possible too:

Personally, I’d use file_put_contents and file_get_contents (these are wrappers for fopen, fputs, etc).

Also, if you are going to write any structured data, such as arrays, I suggest you serialize and unserialize the files contents.

$file = '/tmp/file'; $content = serialize($my_variable); file_put_contents($file, $content); $content = unserialize(file_get_contents($file)); 

(Sorry I can’t comment just yet, otherwise I would)

To add to Christian’s answer you might consider using json_encode and json_decode instead of serialize and unserialize to keep you safe. See a warning from the PHP man page:

Warning

Do not pass untrusted user input to unserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

So your final solution might have the following:

$file = '/tmp/file'; $content = json_encode($my_variable); file_put_contents($file, $content); $content = json_decode(file_get_contents($file), TRUE); 

Источник

Exporting mysql table to .txt or .doc file using PHP

I have a mysql table that keeps a log of messages that users send every day. What I want to do is export the the message log once per day into a text file, and am not sure how to do this. Our server has phpmyadmin, and I can export the table into a text file manually, but I don’t know how to either A) have phpmyadmin export this file automatically once per day, or B) write the exporting in php code. I want the exported files to be available to the users of my site for download. The site it written in php. If there is any other information you need to answer this question, let me know!

5 Answers 5

This simple PHP script will save all the data in a table to a .txt file. Records will be separated by new lines, and fields by a tab character. Here it is:

It will get saved in the same folder as the PHP script. If you want to save it elsewhere, specify the full path, for example: $fh = fopen(‘/var/www/downloads/data.txt’, ‘w’);

Be careful about rolling your own, unless you handle things like NULL, character sets, etc.

query("SELECT * FROM myTable INTO OUTFILE 'data.txt'"); $dummy = $result->fetchAll(); 

The data.txt file will be written on the MySQL server. The directory must be writable by the uid of the mysqld process. It will not overwrite any existing file, and requires that you have the FILE SQL privilege.

Second alternative: use mysqldump to output to flat text file (as @OMG Ponies mentioned):

This works like INTO OUTFILE , it needs to run on the MySQL server host, and the directory must be writable by the mysqld uid.

Third option: run query with mysql client and output text:

mysql -B -e "SELECT * FROM MyTable" > mytable.txt 

This can be run on any host, and requires no special privileges or directory permissions. But NULL may not be handled as it would be with mysqldump or INTO OUTFILE .

Источник

How to Export MySQL Table data as CSV file in PHP

Exporting MySQL table data to a CSV file is a common need in web development. It provide­s the flexibility of converting your database­ records into an easily readable­ and shareable format.

Whether you want to ge­nerate reports, transfe­r data to another system, or create­ backups, knowing how to export MySQL data to CSV using PHP can be incredibly useful.

This article guide­s you through the proce­ss of exporting MySQL table data as a CSV file using PHP.

How to Export MySQL Table data as CSV file in PHP

Table of Content

1. Create a Table

I am using users table in the example.

CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(50) NOT NULL, `gender` varchar(10) NOT NULL, `email` varchar(70) NOT NULL );

2. Establishing a Database Connection

Create a new config.php to define database connection.

4. PHP: Exporting Data to CSV File

Create a download.php file for CSV export.

  • Define a filename for the CSV file as “users.csv”.
  • The serialized data from the textarea, received via the $_POST as export_data , is unserialized using the unserialize() function and stored in the $export_data variable.
  • A file with the specified filename is created using the fopen() function with the “w” mode, allowing writing to the file.
  • Using foreach loop iterate over the unserialized data array, and each line of data is written to the CSV file using the fputcsv() function.
  • Once all data is written, the file is closed using fclose() .

3. Downloading the CSV File:

  • Headers are set to specify the file transfer and instruct the browser to treat the file as an attachment with the provided filename.
  • Set Content-Type header to “application/csv”.
  • The contents of the CSV file are read using the readfile() function, which outputs the file content for download.

After the file has been downloaded, the file is deleted using the unlink() function to remove it from the server.

5. Exiting the Script:

The exit() function is called to terminate the script execution after the file has been downloaded and deleted, preventing any further processing.

 fclose($file); // download header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=".$filename); header("Content-Type: application/csv; "); readfile($filename); // deleting file unlink($filename); exit();

5. Demo

6. Conclusion

The code we discussed offers a simple and straightforward way to export MySQL table data as a CSV file using PHP. By creating an array of the data and using the fputcsv() function, the code effectively writes the content into a file.

This capability provides several advantages for your PHP-based web applications. You can easily generate CSV files for creating reports, analyzing data, sharing information with external systems, and collaborating with others.

When utilizing this code, remember to customize it to fit your specific needs. Ensure that you name the files appropriately and consider any security measures required to protect sensitive data.

If you’re interested in learning how to import CSV file data into a MySQL database table using PHP, you can refer to this tutorial.

If you found this tutorial helpful then don’t forget to share.

Источник

Best way to write arrays to a file? [closed]

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

$lang = array ( 'hello' => 'hello world!' ); 

and be able to edit it from the back office. (then instead of fetching it from the poor db, i would just use $lang[‘hello’]..). what are you suggesting for the best and efficient way to pull it of?

Why do you think your database is poor? My database is rather good at storing and retrieving values, because. oh yeah, that’s what it’s supposed to do 🙂

4 Answers 4

the most efficient way i found looks like this:

build up your array in php somehow and export it into a file using var_export()

file_put_contents( '/some/file/data.php', ' 

then later, wherever you need this data pull it like this

$data = include '/some/file/data.php'; 

i would prefer serialize over var_export. An attacker could put malicious code into the .php containing the variables and it gets executed.

@Mogria Well, if an attacker has access to the language files, he presumably could inject that code into any other file as well. 🙂

@deceze not necessarily, the file you write these variables to needs to be writeable for php. The other files only need to be readable.

you don't need to write the file from a script which is accessible from the outside. the most efficient and fast way to read data arrays is this include. serialize/unserialize needs more memory and cpu and even bytes in the file.

file_put_contents("my_array.json", json_encode($array)); 
$array = json_decode(file_get_contents("my_array.json")); 

Please note that if you want to save disk space (when using very large arrays ie) you can always store it in files as binary data

Well if you insist to put the data into files, you might consider php functions serialize() and unserialize() and then put the data into files using file_put_contents .

 array('pear', 'apple', 'sony') ); file_put_contents('somearray.dat', serialize( $somearray ) ); $loaded = unserialize( file_get_contents('somearray.dat') ); print_r($loaded); ?> 

You can try json_encode() and json_decode() .

write contents of $save to file

$lang = file_get_contents('langfile'); $lang = json_decode($lang, true); 

Источник

Читайте также:  Name sorting in java
Оцените статью