将CSV转换为JSON键值
我有一个这样的CSV文件:
First Name*,Registrarse
Last Name*,Registrarse
Your Email*,Nombre*
Country*,Apellido*
我正在寻找将此转换为JSON,如下所示:
{
"First Name*": "Registrarse",
"Last Name*": "Registrarse"
.....
}
我尝试了像CSV到JSON这样的NPM工具,我无法得到这种效果。有谁知道这样做的方法?
回答如下:您可以将CSV文件转换为关联数组并将其编码为JSON:
$csv = <<<EOF
First Name*,Registrarse
Last Name*,Registrarse
Your Email*,Nombre*
Country*,Apellido*
EOF;
$csvArray = explode(PHP_EOL, $csv);
$jsonArray = array();
foreach ($csvArray as $row) {
preg_match('/(.*?),(.*)/', $row, $matches);
$jsonArray[$matches[1]] = $matches[2];
}
$json = json_encode($jsonArray, JSON_PRETTY_PRINT);
echo $json, PHP_EOL;
输出:
{
"First Name*": "Registrarse",
"Last Name*": "Registrarse",
"Your Email*": "Nombre*",
"Country*": "Apellido*"
}