我有一个看起来像的文本文件:
Line one
Line two
Line three
我想将其转换为:
return array(
'Line one',
'Line two',
'Line three'
);
并将其另存为新文件。我不想一遍又一遍地执行相同的爆炸/ preg_split,这真的没有意义。我只是想从原始文件创建一个静态文件,并在更新原始文件时更新它。
我将如何做到这一点?
答案 0 :(得分:2)
使用file
功能读取文件:
$array = file('file1.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
要输出它,请使用file_put_contents
和implode
:
file_put_contents('file2.txt', implode("\n", $array));
答案 1 :(得分:2)
$array = file($thefile,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
file_put_contents($theotherfile, "return array(\n ".implode(",\n ", $array)."\n);";
答案 2 :(得分:1)
您可以使用var_export()
生成所需的输出。
示例:
$array = array();
for ($i = 0; $i < 10; $i++) {
$array[md5($i)] = sha1($i);
}
echo var_export($array);
结果:
array (
'cfcd208495d565ef66e7dff9f98764da' => 'b6589fc6ab0dc82cf12099d1c2d40ab994e8410c',
'c4ca4238a0b923820dcc509a6f75849b' => '356a192b7913b04c54574d18c28d46e6395428ab',
'c81e728d9d4c2f636f067f89cc14862c' => 'da4b9237bacccdf19c0760cab7aec4a8359010b0',
'eccbc87e4b5ce2fe28308fd9f2a7baf3' => '77de68daecd823babbb58edb1c8e14d7106e83bb',
'a87ff679a2f3e71d9181a67b7542122c' => '1b6453892473a467d07372d45eb05abc2031647a',
'e4da3b7fbbce2345d7772b0674a318d5' => 'ac3478d69a3c81fa62e60f5c3696165a4e5e6ac4',
'1679091c5a880faf6fb5e6087eb1b2dc' => 'c1dfd96eea8cc2b62785275bca38ac261256e278',
'8f14e45fceea167a5a36dedd4bea2543' => '902ba3cda1883801594b6e1b452790cc53948fda',
'c9f0f895fb98ab9159f51fd0297e236d' => 'fe5dbbcea5ce7e2988b8c69bcfdfde8904aabc1f',
'45c48cce2e2d7fbdea1afc51c7c6ad26' => '0ade7c2cf97f75d009975f4d720d1fa6c19f4897',
)