我想在文本文件中写一个php对象。php对象是这样的
$obj = new stdClass();
$obj->name = "My Name";
$obj->birthdate = "YYYY-MM-DD";
$obj->position = "My position";
我想将此$obj写在文本文件中。文本文件位于此路径中
$filePath = getcwd().DIRECTORY_SEPARATOR."note".DIRECTORY_SEPARATOR."notice.txt"
我想要一种简单的方法将此对象写入文本文件,并希望读取该文件以获取我定义的属性。请帮助我。
提前谢谢。
您可以使用以下代码在文本文件中编写 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);
}
要读取文本文件以获取定义的属性,请执行以下操作...
$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;
}
}
您可以在将
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
然后稍后你可以反序列化():
$obj = unserialize(file_get_contents($file));
echo $obj->birthdate;//YYYY-MM-DD
相反,我们可以使用以下方法将整个对象写入文件中。
$fp = fopen('D:'file_name.txt', 'w');
fwrite($fp, print_r($obj, true));
fclose($fp);
因此,在 print_r() 函数中,我们需要传递对象和 true 参数,它将信息返回到 fwrite() 函数而不是打印它。