20

I want to write a php object in a text file. The php object is like that

 $obj = new stdClass();
 $obj->name = "My Name";
 $obj->birthdate = "YYYY-MM-DD";
 $obj->position = "My position";

I want to write this $obj in a text file. The text file is located in this path

$filePath = getcwd().DIRECTORY_SEPARATOR."note".DIRECTORY_SEPARATOR."notice.txt"

I want a simple way to write this object into the text file and want to read the file to get the properties as I defined. Please help me.

Thanks in advance.

Nantu
  • 557
  • 1
  • 4
  • 16

3 Answers3

29

You can use the following code for write php object in the text file...

$obj = new stdClass();
$obj->name = "My Name";
$obj->birthdate = "YYYY-MM-DD";
$obj->position = "My position";

$objData = serialize( $obj);
$filePath = getcwd().DIRECTORY_SEPARATOR."note".DIRECTORY_SEPARATOR."notice.txt";
if (is_writable($filePath)) {
    $fp = fopen($filePath, "w"); 
    fwrite($fp, $objData); 
    fclose($fp);
}

To read the text file to get the properties as you defined...

$filePath = getcwd().DIRECTORY_SEPARATOR."note".DIRECTORY_SEPARATOR."notice.txt";
if (file_exists($filePath)){
    $objData = file_get_contents($filePath);
    $obj = unserialize($objData);           
    if (!empty($obj)){
        $name = $obj->name;
        $birthdate = $obj->birthdate;
        $position = $obj->position;
    }
}
Developer
  • 306
  • 2
  • 3
  • Perfect! I like this. Thanks a lot. – Nantu Sep 08 '13 at 08:34
  • is_writable($filePath) did not work for me, because it includes the file. My path was actually writable, but is_writable was only true without filename. – Ralf Sep 09 '19 at 12:41
9

You can use serialize() before saving it to the file and then unserialize() to get the whole $obj available to you:

 $obj = new stdClass();
 $obj->name = "My Name";
 $obj->birthdate = "YYYY-MM-DD";
 $obj->position = "My position";
 $objtext = serialize($obj);
 //write to file

Then later you can unserialize():

 $obj = unserialize(file_get_contents($file));
 echo $obj->birthdate;//YYYY-MM-DD
1

Instead we can use following method to write whole object in the file.

$fp = fopen('D:\file_name.txt', 'w');        
fwrite($fp, print_r($obj, true));
fclose($fp);

So, inside print_r() function we need to pass object and true parameter which will return the information to fwrite() function rather than printing it.

Exception
  • 789
  • 4
  • 18