[英]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.