文件放内容与数组

Shi*_*ant 13 php

我正在使用file_put_contents($file, $data);函数将内容放入文件中,因为这些文件是在会话名称的飞行中创建的,$ data是一个多维数组,当我回显数组时,它打印出来很好但在文件中没有内容被记录,除了单词排列

我应该做什么或者是否有任何其他功能自动创建文件并记录数据(数组)?

谢谢.

Phi*_*ber 29

你想要写入serialize()数组,并unserialize()在读取文件后.

$array = array('foo' => 'bar');
file_put_contents('foo.txt', serialize($array));
$array = unserialize(file_get_contents('foo.txt')));
Run Code Online (Sandbox Code Playgroud)

哦,我现在真的不知道你如何回应阵列,但echo array('foo' => 'bar');总会打印出来Array.


Rob*_*air 7

或者,如果您想返回一个在 txt 文件中更易于阅读的格式化数组,请使用print_r

如果您想捕获 print_r() 的输出,请使用返回参数。当此参数设置为 TRUE 时,print_r()将返回信息而不是打印它。

代码是:

$txt = "<pre>".print_r($data, true)."</pre>";
file_put_contents('file.txt', $txt);
Run Code Online (Sandbox Code Playgroud)


小智 5

如果你想让它可读,你可以这样做:

<?php
ob_start();
print_r($data);
$textualRepresentation = ob_get_contents();
ob_end_clean();

file_put_contents($file, $textualRepresentation);
?>
Run Code Online (Sandbox Code Playgroud)

  • $textualRepresentation = print_r($data, true); 会做的很好:-) (5认同)