如何从csv文件中获取此json。 csv文件包含标题:
Description, BusinessSurname, IsCustomer, IsSupplier, AddressType, BusinessAddress, IsInternational
第一行:
Contact1, Contact1, True, True, Business, 123 Fake St, False
我需要csv中的数据转换为精确的json,但是需要它来循环可能存在的任何其他行。
{
Description:'Contact1',
SurnameBusinessName:'Contact1',
IsCustomer:True,
IsSupplier:True,
Addresses:
[
{AddressType:'Business',Line1:'123 Fake St',IsInternational:False},
]
}
我无法让它发挥作用。请帮忙。
########################################
我找到了答案,在尝试了所有可能的解决方案后,我意识到我必须手动创建json,因为没有json或数组会给我我想要的确切内容。但是我已经放弃了这个API端点,并且没有嵌套就更简单了。由于json格式的严格性,这个API将接受我基本上将我的csv中的每个值分配给变量并手动创建所需的json。虽然下面的代码是针对Accounts端点的,但我可以对任何端点使用完全相同的方法,因为我有点手动创建json。它是唯一可以工作的方式我认为有些字段是像AccountName这样的字符串,有些整数像AcountType。
$file = 'acc.csv';
$mode = 'r';
$handle = fopen($file, $mode);
while(($csv = fgetcsv($handle)) !==FALSE){
foreach($csv as $row => $value){
$data = $row.$value;
switch ($row){
case '0':
$accounttype = $value;
break;
case '1':
$accountname = $value;
break;
case '2':
$hint = $value;
break;
case '3':
$status = $value;
break;
case '4':
$sortorder = $value;
break;
case '5':
$accountcode = $value;
break;
case '6':
$parentaccountcatid = $value;
$json = "
{
AccountType:" . $accounttype . ",
AccountName:'" . $accountname . "',
Hint:'" . $hint . "',
Status:" . $status . ",
SortOrder:" . $sortorder . ",
AccountCode:'" . $accountcode . "',
ParentAccountingCategoryID:'" . $parentaccountcatid . "'
}";
//echo $json;
答案 0 :(得分:0)
脚本
[akshay@localhost tmp]$ cat test.php
<?php
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 0, $delimiter)) !== FALSE)
{
if(!$header)
{
// if you want keys with space char then
// $header = $row;
// I prefer trimming
$header = array_map('trim',$row);
}
else
{
if(count($header)!=count($row)){ continue; }
$data[] = array_combine($header, $row);
}
}
fclose($handle);
}
return $data;
}
print_r(json_encode(csv_to_array("/tmp/test.csv"),JSON_PRETTY_PRINT));
?>
示例csv文件
[akshay@localhost tmp]$ cat test.csv
Description, BusinessSurname, IsCustomer, IsSupplier, AddressType, BusinessAddress, IsInternational
Contact1, Contact1, True, True, Business, 123 Fake St, False
执行
[akshay@localhost tmp]$ php test.php
[
{
"Description": "Contact1",
"BusinessSurname": " Contact1",
"IsCustomer": " True",
"IsSupplier": " True",
"AddressType": " Business",
"BusinessAddress": " 123 Fake St",
"IsInternational": " False"
}
]