[英]Export row from CSV file to JSON
我想使用require将CSV文件中的一行导出到JSON文件:CSV中的1行导出1文件JSON。 我成功导出文件,但是无法过滤我要导出的行。 谁能帮我?
<?php
header('Content-type: application/json');
$feed = 'jsondata_palpad.csv';
$keys = array();
$newArray = array();
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
$data = csvToArray($feed, ',');
$count = count($data) - 1;
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
//Xuat file JSON
for ($i = 0; $i < 5; $i++) {
$json = json_encode($newArray[$i]);
echo $json . "<br />\n";
$filename = $data[$i][1] . ".json";
echo $filename . "<br />\n";
//echo "title[" . $data[$i][4] . "]";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
}
?>
如果建议= 2,则将导出id为2的行。 我想ID,PRODUCT_ID,标题,大纲导出到JSON文件。这个是样品JSON文件: http://img839.imageshack.us/img839/5277/21527799.png这是CSV文件: HTTP://img690.imageshack .us / img690 / 1526 / 43004273.png
您正在循环浏览csv文件的所有6行并将其保存到JSON文件:
for ($i = 0; $i < 5; $i++) {
...
}
如果知道所需的行号,则不要遍历每一行-只需在该行的循环内调用代码即可。 例如,如果您想要第二行:
$row_we_want = 1;
$json = json_encode($newArray[$row_we_want]);
$filename = $data[$row_we_want][1] . ".json";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
如果不确定是哪一行,并且需要检查每一行,则可以在循环中进行检查:
for ($i = 0; $i < 5; $i++) {
if (some_condition) {
$json = json_encode($newArray[$i]);
$filename = $i][1] . ".json";
$handle = fopen("./" . $filename, "w");
fwrite($handle, $json);
fclose($handle);
}
}
如果不是总是固定长度的话,也可以使用count
函数用数组的长度替换循环中的5。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.