Write and read php object in a text file?

家住魔仙堡 提交于 2019-12-03 09:38:48

问题


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.


回答1:


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;
    }
}



回答2:


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


来源:https://stackoverflow.com/questions/18681090/write-and-read-php-object-in-a-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!