4

i am trying to store data in a text file, something like an array into a text file using php instead of storing into mysql database.

for example here are the data to be stored in a text file

name=>john
age=>25
location=>australia

then after saving it to a text file , how can I get the contents out and parse it with php , for like php can find the name , age and location and echo it out(something like parsing an array)

I need it for storing the data into a text file so it can be easily access from other domains without requiring to be on the same domain , connect to database , get the data from database. I am looking for a speedy solution. :)

I'm not sure which direction should I look into for this kind of functionality , hoping someone can point me out.

sm21guy
  • 616
  • 2
  • 12
  • 32
  • probably xml if you must, but a database would be the best option –  Sep 11 '12 at 08:26
  • which is faster? xml or database? – sm21guy Sep 11 '12 at 08:32
  • `json_encode` and `json_decode` should worth a try. – Passerby Sep 11 '12 at 08:32
  • Please let us know why you need to store and read the data and why you do not want to use a DB. Then we might give a more appropriate solution. – Thorsten Niehues Sep 11 '12 at 08:32
  • I need it for storing the data into a text file so it can be easily access from other domains without requiring to be on the same domain , connect to database , get the data from database. I am looking for a speedy solution. :) – sm21guy Sep 11 '12 at 08:34
  • Then you might want to use XML - but I suggest using a DB is very easy to store the data. And also easy for others to access the data. Performance should be good with both solutions – Thorsten Niehues Sep 11 '12 at 08:44
  • db, faster,easier to maintain, scalable, designed for the job - flat file - none of the above. –  Sep 11 '12 at 09:20
  • Possible duplicate of [Save PHP variables to a text file](https://stackoverflow.com/questions/2995461/save-php-variables-to-a-text-file) – slhck Dec 30 '18 at 14:53

6 Answers6

15

Storing:
1. Use serialize() to serialize your array into a string
2. Write that string to text file using file_put_contents()

Reading:
1. Use file_get_contents to read text file
2. Use unserialize() to unserialize previously serialized array

serialize()/unserialize() can be replaced by json_encode()/json_decode()

Māris Kiseļovs
  • 16,389
  • 5
  • 39
  • 48
1

You should make a uniqid then they won't be able to access any other txt files in the server.

<?php

    #Get a secure filename
    $username = "myUsername"
    $filename = uniqid($username, true).".txt";

    //Create the array
    $userInfo = ["username" => $username, "points" => 0];

    // Store the data
    file_put_contents($filename, serialize($userInfo));

    // How to get the data
    $userInfo = unserialize(file_get_contents($filename));
    print($userInfo["points"]);
    //or
    print($userInfo["username"]);

?>
CCjump21
  • 68
  • 1
  • 7
0

You may use

In case you want to convert the array to an XML you might want to read this post: How to convert array to SimpleXML

Community
  • 1
  • 1
Thorsten Niehues
  • 12,854
  • 19
  • 73
  • 105
0

These functions should do what you want :

function storeInTextFile($array,$path) {
    if(file_exists($path)) {
         $handle = fopen($path,'wb');
         fwrite($handle, arrayToString($array));
         fclose($handle);
    }
}

function arrayToString($array) {
    $string = '';
    foreach($array as $key => $value) {
        $string .= "{$key} => {$value}\n";
    }
    return $string;
}

function stringToArray($string) {
    $explodedString = explode('\n',$string);
    $returnArray = array();
    foreach($explodedString as $arrayValue) {
        list($key,$value) = explode(' => ',$arrayValue);
        $returnArray[$key] = $value;
    }

    return $returnArray;
}
jbrtrnd
  • 3,755
  • 5
  • 24
  • 41
0

//-- short -------------------------------------------

$data = [ "a" => "A",  "b" => "B", "c" => "C" ];
  echo '<br> data - array: ';
  var_dump($data);

file_put_contents('db.php', json_encode($data) );

//get
$g = json_decode(file_get_contents('db.php') , 1);  // 1 Array , 0  Object

  echo '<br><hr>short: var_dump($g): ';
  var_dump($g);    

//-- long -------------------------------------------//

$data = [ "a" => "A",  "b" => "B", "c" => "C" ];
  echo '<br> data - array: ';
  var_dump($data);
  echo '<br> json_encode($data): ';

$jdata = json_encode($data);
  var_dump($jdata); 
  echo'<hr>';
file_put_contents('db.php', $jdata);

//get
$jg = file_get_contents('db.php');
  echo ' $jg = file_get_contents(\'db.php\'); $jg : ';
  var_dump($jg);

  echo '<br> json_decode($jg , 1) //1 Array<br>';
$g = json_decode($jg , 1);  
  var_dump($g);

  echo '<br> json_decode($jg , 0)  //0 Object<br>';
$g = json_decode($jg , 0);
  var_dump($g);
And
  • 65
  • 2
  • 7
-1

I made a tiny library (~2 KB; <100 lines) that allows you to do just this: varDx

It has functions to write, read, modify, check and delete data. It implements serialization, and therefore supports all data types.

Here's how you can use it:

<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file

$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file
undo
  • 239
  • 3
  • 18