(PHP 5 >= 5.1.0, PHP 7, PHP 8)
fputcsv — Format line as CSV and write to file pointer
$stream,$fields,$separator = ",",$enclosure = "\"",$escape = "\\",$eol = "\n"
fputcsv() formats a line (passed as a
fields array) as CSV and writes it
(terminated by a eol) to the specified
stream.
streamIl puntatore al file deve essere valido, e deve puntare ad un file aperto con successo da fopen() o fsockopen() (e non ancora chiuso da fclose()).
fieldsAn array of strings.
separator
Il parametro separator imposta il separatore di campo.
Deve essere un carattere a byte singolo.
enclosure
Il parametro enclosure imposta il carattere di chiusura del campo.
Deve essere un carattere a byte singolo.
escape
Il parametro escape imposta il carattere di escape.
Deve essere un carattere a byte singolo o la stringa vuota.
La stringa vuota ("") disabilita il meccanismo di escape proprietario.
Nota: Di solito, per effettuare l'escape di un carattere
enclosureall'interno di un campo lo si duplica; tuttavia, il carattereescapepuò essere usato come alternativa. Pertanto, con i valori predefiniti del parametro""e\"hanno lo stesso significato. Oltre a consentire di effettuare l'escape del carattereenclosure, il carattereescapenon ha significato speciale; non è nemmeno destinato ad effettuare l'escape di se stesso.
A partire da PHP 8.4.0, dipendere dal valore predefinito di
escape è deprecato.
Deve essere fornito esplicitamente, sia per posizione che mediante l'uso
dei named arguments.
eol
The optional eol parameter sets
a custom End of Line sequence.
When escape is set to anything other than an empty string
("") it can result in CSV that is not compliant with
» RFC 4180 or unable to survive a roundtrip
through the PHP CSV functions. The default for escape is
"\\" so it is recommended to set it to the empty string explicitly.
The default value will change in a future version of PHP, no earlier than PHP 9.0.
Nota:
If an
enclosurecharacter is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by anescape.
Returns the length of the written string o false in caso di fallimento.
Genera un ValueError se
separator o enclosure
non sono lunghi un byte.
Genera un ValueError se
escape non è lungo un byte o è una stringa vuota.
| Versione | Descrizione |
|---|---|
| 8.4.0 |
L'affidamento sul valore predefinito di escape è ora
deprecato.
|
| 8.1.0 |
The optional eol parameter has been added.
|
| 7.4.0 |
The escape parameter now also accepts an empty
string to disable the proprietary escape mechanism.
|
Example #1 fputcsv() example
<?php
$list = [
['aaa', 'bbb', 'ccc', 'dddd'],
['123', '456', '789'],
['"aaa"', '"bbb"']
];
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields, ',', '"', '');
}
fclose($fp);
?>The above example will write the following to file.csv:
aaa,bbb,ccc,dddd 123,456,789 """aaa""","""bbb"""