Class luya\yii\helpers\ImportHelper
Inheritance | luya\yii\helpers\ImportHelper |
---|---|
Subclasses | luya\helpers\ImportHelper |
Available since version | 1.0.0 |
Source Code | https://github.com/luyadev/yii-helpers/blob/master/src/helpers/ImportHelper.php |
Import from Formats to Array.
Public Methods
Method | Description | Defined By |
---|---|---|
csv() | Import a CSV from a string or filename and return array. | luya\yii\helpers\ImportHelper |
Method Details
Import a CSV from a string or filename and return array.
The filename can be either a resource from fopen() or a string containing the csv data. Filenames will be wrapped trough {{Yii::getAlias()}} method.
public static array csv ( $filename, array $options = [] ) | ||
$filename | string |
Can be either a filename which is parsed by {{luya\yii\helpers\FileHelper::getFileContent()}} or a string with the contained csv data. |
$options | array |
Provide options to the csv
|
return | array |
An array with the csv data. |
---|
public static function csv($filename, array $options = [])
{
$filename = Yii::getAlias($filename);
// check if a given file name is provided or a csv based on the content
if (FileHelper::getFileInfo($filename)->extension) {
$resource = fopen($filename, 'r');
} else {
$resource = fopen('php://memory', 'rw');
fwrite($resource, $filename);
rewind($resource);
}
$data = [];
while (($row = fgetcsv($resource, 0, ArrayHelper::getValue($options, 'delimiter', ','), ArrayHelper::getValue($options, 'enclosure', '"'))) !== false) {
$data[] = $row;
}
fclose($resource);
// check whether only an amount of fields should be parsed into the final array
$fields = ArrayHelper::getValue($options, 'fields', false);
if ($fields && is_array($fields)) {
$filteredData = [];
foreach ($fields as $fieldColumn) {
if (!is_numeric($fieldColumn)) {
$fieldColumn = array_search($fieldColumn, $data[0]);
}
foreach ($data as $key => $rowValue) {
if (array_key_exists($fieldColumn, $rowValue)) {
$filteredData[$key][] = $rowValue[$fieldColumn];
}
}
}
$data = $filteredData;
unset($filteredData);
}
// if the option to remove a header is provide. remove the first key and reset and array keys
if (ArrayHelper::getValue($options, 'removeHeader', false)) {
unset($data[0]);
$data = array_values($data);
}
return $data;
}