Csv::parseUpload
Read a CSV file sent with a form
Description
public static array Csv::parseUpload( string $field [, array $options = array() ] )
Reads the file sent in the file input $field from PHP's temporary file and returns its rows as parse() does. Nothing is stored. Error messages start with the name of the sent file.
Only a file that PHP received as an upload in this request is read (is_uploaded_file()), with a name ending in .csv or .txt, of at most max_size bytes.
Throws \RuntimeException when:
- no file was sent, or more than one in the field;
- the file is larger than PHP accepts (
upload_max_filesize) or thanmax_size; - the upload failed;
- the name does not end in
.csvor.txt; - a row is broken or a title of
columnsis missing.
Arguments
| Name | Data type | Default | Remarks |
|---|---|---|---|
| $field | string | Name of the file input | |
| $options | array | array() | max_size (bytes, default 5 * 1024 * 1024: 5 MB), and header, columns, encoding of parse() |
Example
Template
<form action="{{ $site.prefix }}/import" method="post" enctype="multipart/form-data">
{{ include '/cms/parts/csrf' }}
<input type="file" name="csv" accept=".csv">
<button type="submit">Import</button>
</form>
CMS controller
use Fegg\Tool\Csv;
try {
$rows = Csv::parseUpload('csv', array(
'header' => true,
'columns' => array('タイトル' => 'title', '投稿日' => 'post_date'),
'max_size' => 1024 * 1024,
));
} catch (\RuntimeException $e) {
$this->page['error'] = array($e->getMessage());
$this->displayPage($this->page['prefix'] . '/import');
}
The whole import, with the check of every row: Importing a file.