ruifernandees / csv-json-converter
现代PHP CSV到JSON和JSON到CSV转换器
v0.0.2
2020-12-23 16:06 UTC
Requires (Dev)
README
您可以在以下位置查看README:
📄 描述
CSV/JSON转换器是一个现代的PHP组件,它抽象了CSV到JSON和JSON到CSV的转换过程。
安装
使用Composer
$ composer require ruifernandees/csv-json-converter
💻 使用
CSV -> JSON
此示例在examples/csvToJson.php中
代码
<?php require __DIR__ . '/../vendor/autoload.php'; use RuiF\CsvToJson\FileFacade; $filePath = __DIR__ . "/users.csv"; if (file_exists($filePath)) { $fileFacade = new FileFacade(); /** * Is the line on the CSV file that the keys are (Like name, age, and city) */ $lineOfCsvKeysOnTheFile = 1; /** * -1 if you want to get all lines of the CSV file (after the keys). * If you want to limit, you can pass any number greater than zero * (See the examples below) */ $limitOfLines = 1; /** * Is the start position after the keys that * you want to consider when converting: 0 is the first position * (See the examples below) */ $offset = 0; $json = $fileFacade->convertCsvToJson($filePath, $lineOfCsvKeysOnTheFile, $limitOfLines, $offset); echo $json; } else { echo "The file doesn't exists"; }
输入文件(users.csv)
name,age,city
Rui,18,Maceió
José,25,São Paulo
输出(限制为1,偏移为0)
[ { "name": "Rui", "age": "18", "city": "Maceió" } ]
输出(限制为1,偏移为1)
[ { "name": "José", "age": "25", "city": "São Paulo" } ]
输出(使用默认限制和偏移,获取CSV文件的全部元素)
[ { "name": "Rui", "age": "18", "city": "Maceió" }, { "name": "José", "age": "25", "city": "São Paulo" } ]
您可以使用以下代码保存JSON文件:
$jsonFile = __DIR__ . "/users.json"; $fileOpen = fopen($jsonFile, "w"); fwrite($fileOpen, $json);
JSON -> CSV
此示例在examples/jsonToCsv.php中
代码
<?php require __DIR__ . '/../vendor/autoload.php'; use RuiF\CsvToJson\FileFacade; $filePath = __DIR__ . '/users.json'; if (file_exists($filePath)) { $fileFacade = new FileFacade(); $csv = $fileFacade->convertJsonToCsv($filePath); echo "Result:\n{$csv}"; } else { echo "The file doesn't exists"; }
输入文件(users.json)
[ { "name": "Rui", "age": "18", "city": "Maceió" }, { "name": "José", "age": "25", "city": "São Paulo" } ]
输出
name,age,city
Rui,18,Maceió
José,25,São Paulo
您可以使用以下代码保存CSV文件:
$csvFile = __DIR__ . "/users.csv"; $fileOpen = fopen($csvFile, "w"); fwrite($fileOpen, $csv);
运行测试
$ composer test
贡献
有关详细信息,请参阅CONTRIBUTING。
鸣谢
许可证
MIT许可证(MIT)。有关更多信息,请参阅许可证文件。