在文本文件中写入和读取 php 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18681090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:00:41  来源:igfitidea点击:

Write and read php object in a text file?

phpfilefopenfread

提问by Nantu

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

我想在文本文件中编写一个 php 对象。php 对象就是这样

 $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

我想把这个 $obj 写在一个文本文件中。文本文件位于此路径中

$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.

提前致谢。

回答by Developer

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

您可以使用以下代码在文本文件中写入 php 对象...

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

回答by Nantu

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

您可以serialize()在将其保存到文件之前使用,然后unserialize()让整个文件$obj可供您使用:

 $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