gpt4 book ai didi

PHP将对象转换为字符串

转载 作者:行者123 更新时间:2023-12-02 07:05:21 24 4
gpt4 key购买 nike

我打算将返回的对象保存到文件中,以便稍后下载查看。为清楚起见,我正在使用外部 API 服务,并收集它们的数据,以便解析到另一个数据库中。

这是我所拥有的:

<?php
require('class.php');
$client = new connect2Them();
$logged_in = $client->login();
if(!$logged_in){
echo "Not connected!"; die();
}

$records = $client->get_records();
if(count($records < 1){
echo "No records found"; die();
}

$singlerecord = $records[0];
print_r($singlerecord);

?>

print_r() 工作正常,我得到了非常大量的数据。我是通过命令行来做这一切的,所以我想把它保存到一个文本文件中。

我在我的 $singlerecord 下添加了这个:

<?php
$myFile = "reviewLater.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $singlerecord;
fwrite($fh, $stringData);
fclose($fh);

?>

我从 PHP 中得到这个错误:PHP 警告:fwrite() 期望参数 2 是字符串,对象在....中给出。

如何将 print_r() 放入 reviewLater.txt?

最佳答案

对象可以用 PHP 的 serialize() 函数序列化并保存到文件中。以后你可以unserialize() 如果你想再次使用它们。

$stringData = serialize($singlerecord);

有趣的事实:这是将对象缓存到文件的一种方法。

引用:http://php.net/manual/en/function.serialize.php

关于PHP将对象转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13259754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com