在文本文件中写入和读取php对象? [英] Write and read php object in a text file?

查看:82
本文介绍了在文本文件中写入和读取php对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想将此$ obj写入文本文件.文本文件位于此路径

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.

谢谢.

推荐答案

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

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

这篇关于在文本文件中写入和读取php对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆