PHP将字符串数据写入文件

时间:2015-04-25 11:46:25

标签: php

如何使用PHP将数据写入文件?

以下是需要编写的示例:

    $filename = 'test.txt';
    $keysize = '2048';
    $dname = 'www.domain.com';

test.txt文件的最终结果应如下所示

[ req ]
bits = 2048
domain_name = www.domain.com

2 个答案:

答案 0 :(得分:1)

使用file_put_contents

$output = "[ req ] \nbits = $keysize\ndomain_name = $dname";
file_put_contents($filename, $output);

\n开辟了一条新线。我可以将$keysize等放在字符串本身中,因为我使用"来创建字符串 - 它不适用于'。请参阅此相关的SO问题:What is the difference between single-quoted and double-quoted strings in PHP?

答案 1 :(得分:-1)

PHP脚本是:

<?php
$output = "[ req ]"."<br>";
$output .= "bits = ".$keysize."<br>";
$output .= "domain_name = ".$dname."<br>";
$handle = fopen($filename , 'w');
$write =  fwrite($handle, $output);
fclose($handle);
?>