PHP를 사용하여 CSV를 JSON으로 변환
PHP를 사용하여 CSV 파일을 JSON으로 변환하려고 합니다.
여기 제 코드가 있습니다.
<?php
date_default_timezone_set('UTC');
$today = date("n_j"); // Today is 1/23/2015 -> $today = 1_23
$file_name = $today.'.CSV'; // My file name is 1_23.csv
$file_path = 'C:\\Users\\bheng\\Desktop\\qb\\'.$file_name;
$file_handle = fopen($file_path, "r");
$result = array();
if ($file_handle !== FALSE) {
$column_headers = fgetcsv($file_handle);
foreach($column_headers as $header) {
$result[$header] = array();
}
while (($data = fgetcsv($file_handle)) !== FALSE) {
$i = 0;
foreach($result as &$column) {
$column[] = $data[$i++];
}
}
fclose($file_handle);
}
// print_r($result); // I see all data(s) except the header
$json = json_encode($result);
echo $json;
?>
print_r($result);
// 모든 데이터가 표시됨
그러면 나는json_encode($result);
표시하려고 했지만 화면에 아무것도 표시되지 않습니다.화면에 아무것도 표시되지 않고, 에러 메세지가 0 밖에 표시되지 않습니다.
내가 뭘 잘못하고 있는 거야? 누가 나 좀 도와줄 수 있어?
결과 추가
print_r($result);
Array (
[Inventory] => Array (
[0] => bs-0468R(20ug)
[1] => bs-1338R(1ml)
[2] => bs-1557G(no bsa)
[3] => bs-3295R(no BSA)
[4] => bs-0730R-Cy5"
[5] => bs-3889R-PE-Cy7"
[6] => 11033R
[7] => 1554R-A647
[8] => 4667
[9] => ABIN731018
[10] => Anti-DBNL protein
.... more ....
다음과 같이 시도합니다.
$file="1_23.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json = json_encode($array);
print_r($json);
data.csv
게임, 스킬
보물 사냥꾼, 필리팔라
로켓 발사대, 비보비보
로켓 엔진, 헤호호
열 이름을 사용하여 변환하는 방법은 다음과 같습니다.
csv2json.php
<?php
if (($handle = fopen("data.csv", "r")) !== FALSE) {
$csvs = [];
while(! feof($handle)) {
$csvs[] = fgetcsv($handle);
}
$datas = [];
$column_names = [];
foreach ($csvs[0] as $single_csv) {
$column_names[] = $single_csv;
}
foreach ($csvs as $key => $csv) {
if ($key === 0) {
continue;
}
foreach ($column_names as $column_key => $column_name) {
$datas[$key-1][$column_name] = $csv[$column_key];
}
}
$json = json_encode($datas);
fclose($handle);
print_r($json);
}
출력 결과
[
{
"Game": "Treasure Hunter",
"Skill": "pilipala"
},
{
"Game": "Rocket Launcher",
"Skill": "bibobibo"
},
{
"Game": "Rocket Engine",
"Skill": "hehehohoho"
}
]
이쪽도 시도해 보세요.
<?php
function csvtojson($file,$delimiter)
{
if (($handle = fopen($file, "r")) === false)
{
die("can't open the file.");
}
$csv_headers = fgetcsv($handle, 4000, $delimiter);
$csv_json = array();
while ($row = fgetcsv($handle, 4000, $delimiter))
{
$csv_json[] = array_combine($csv_headers, $row);
}
fclose($handle);
return json_encode($csv_json);
}
$jsonresult = csvtojson("./doc.csv", ",");
echo $jsonresult;
비슷한 문제가 발생했는데, JSON으로 인코딩하기 전에 어레이에서 데이터를 UTF-8로 재귀적으로 변환했습니다.
function utf8_converter($array)
{
array_walk_recursive($array, function(&$item, $key){
if(!mb_detect_encoding($item, 'utf-8', true)){
$item = utf8_encode($item);
}
});
return $array;
}
송신원: http://nazcalabs.com/blog/convert-php-array-to-utf8-recursively/
이 문제는 이제 꽤 오래되었지만, 제가 발견한 가장 간단한 예처럼 보였기 때문에 누군가 도움이 되기를 바랍니다. 그리고 저는 이것이 개발자들이 초보자로서 해야 할 꽤 흔한 일이라는 것을 알고 있습니다. 그리고 많은 답변들이 마술에 대해 얼버무리고 있습니다.
$file = storage_path('app/public/waitlist_users_test.csv'); //--> laravel helper, but you can use any path here
function csv_to_json($file)
{
// file() loads each row as an array value, then array map uses the 'str_getcsv' callback to
$csv = array_map('str_getcsv', file($file));
// array_walk - "walks" through each item of the array and applies the call back function. the & in "&row" means that alterations to $row actually change the original $csv array, rather than treating it as immutable (*sort of immutable...)
array_walk($csv, function(&$row) use ($csv) {
// array_combine takes the header row ($csv[0]) and uses it as array keys for each column in the row
$row = array_combine($csv[0], $row);
});
array_shift($csv); # removes now very redundant column header --> contains {'col_1':'col_1', 'col_2':'col_2'...}
$json = json_encode($csv);
return $json;
}
위에서 자세히 설명하지 못한 콜백 기능을 사용할 수 있는 이러한 기능에는 많은 마법이 진행되고 있습니다.저는 독학으로 수년간 프로그래밍을 해왔습니다만, 콜백의 동작에 대해 자세히 설명하지 않고 그냥 얼버무리는 경우가 많습니다.따라서 array_map('str_getcsv', file($file) 함수에 대해 조금 더 자세히 설명하겠습니다.작성된 함수를 전달하거나 php 함수 이름에 문자열로 삽입하면 이 함수는 어떤 값이든 상관없습니다.case - array )요소는 호출함수(이 경우 array_map)에 의해 평가되며, 변수를 명시적으로 전달할 필요 없이 콜백함수에 전달됩니다.요령만 익히면 매우 도움이 됩니다.하지만, 그 설명은 매우 빈번하지 않기 때문에, 초보자는 그 이유를 이해할 수 없습니다.그냥 작동합니다..
위의 링크에 대해 설명했습니다만, 조금 더 자세히 설명하겠습니다.str-getcsv do?어레이 워크 어레이 맵콜러블/콜백
@MoonCactus가 지적한 바와 같이 file() 함수는 한 번에 1행만 로드하므로 큰 .csv 파일의 메모리 사용량을 절약할 수 있습니다.
또한 일부 다른 게시물은 bread를 사용하여 참조합니다.행 해석에 str_getcsv() 대신 bread()를 사용하면 어떨까요? bread()는 문자열의 일부 또는 이스케이프 문자를 올바르게 처리하지 않기 때문입니다.
누가 도움이 됐으면 좋겠네요!
CSV 는, 파라메타 「CSV」, URL 「」)에 를 수 .url=http://example.com/some.csv
최신 버전이 표시됩니다.
<?php
// Lets the browser and tools such as Postman know it's JSON
header( "Content-Type: application/json" );
// Get CSV source through the 'url' parameter
if ( isset( $_GET['url'] ) ) {
$csv = explode( "\n", file_get_contents( $_GET['url'] ) );
$index = str_getcsv( array_shift( $csv ) );
$json = array_map(
function ( $e ) use ( $index ) {
return array_combine( $index, str_getcsv( $e ) );
}, $csv
);
}
else {
$json = "Please set the path to your CSV by using the '?url=' query string.";
}
// Output JSON
echo json_encode( $json );
@Whirlwind의 솔루션과 유사한 방법을 사용하지만 보다 표준적인 JSON 결과를 반환하는 대체 솔루션(각 객체/레코드마다 명명된 필드 포함):
// takes a string of CSV data and returns a JSON representing an array of objects (one object per row)
function convert_csv_to_json($csv_data){
$flat_array = array_map("str_getcsv", explode("\n", $csv_data));
// take the first array item to use for the final object's property labels
$columns = $flat_array[0];
for ($i=1; $i<count($flat_array)-1; $i++){
foreach ($columns as $column_index => $column){
$obj[$i]->$column = $flat_array[$i][$column_index];
}
}
$json = json_encode($obj);
return $json; // or just return $obj if that's a more useful return value
}
은 '어느끼다,느끼다,느끼다를사용합니다.file_get_contents()
, 에 읽습니다.explode()
배열로 만들 수 있습니다.
그러나 더 빠르고, 더 작고, 더 유용하게 만들 수 있습니다.
function ReadCsv($fn)
{
$lines= file($fn); // read file directly as an array of lines
array_pop($lines); // you can remove the last empty line (if required)
$json= json_encode(array_map("str_getcsv", $lines), JSON_NUMERIC_CHECK);
print_r($json);
}
Nb: ★★★★★★★★★★★★★★★★★★★★」JSON_NUMERIC_CHECK
숫자가 문자열로 이중 인용되는 것을 피하기 위해 여기에 있습니다.또한 출력 크기를 줄이고 일반적으로 반대쪽에서 javascript(예: 데이터 계산 또는 플롯)에 도움이 됩니다.하세요!
데이터를 키/밸류 형식으로 변환하는 @ian-d-miller의 솔루션은 마음에 들었지만, 코드에 문제가 계속 있었습니다.
다음과 같은 이점이 있습니다.
function convert_CSV_to_JSON($csv_data){
// convert csv data to an array
$data = array_map("str_getcsv", explode("\n", $csv_data));
// use the first row as column headers
$columns = $data[0];
// create array to hold our converted data
$json = [];
// iterate through each row in the data
foreach ($data as $row_index => $row_data) {
// skip the first row, since it's the headers
if($row_index === 0) continue;
// make sure we establish each new row as an array
$json[$row_index] = [];
// iterate through each column in the row
foreach ($row_data as $column_index => $column_value) {
// get the key for each entry
$label = $columns[$column_index];
// add this column's value to this row's index / column's key
$json[$row_index][$label] = $column_value;
}
}
// bam
return $json;
}
사용방법:
// as is
$json = convert_CSV_to_JSON($csv);
// encoded
$json = json_encode($json);
에게 도움이 될 수 것를 오브젝트오브젝트)가 있는 합니다.이것에 의해, CSV가 오브젝트를 가지는 JSON 어레이로 변환됩니다.(key => value
를 클릭합니다.
function csv2json($a, $e = true) {
$b = ["\r\n","\r","\n",];
foreach ($b as $c => $d) {
$a = explode($d, $a);
$a = isset($b[$c + 1]) ? implode($b[$c + 1], $a) : implode(PHP_EOL, $a);
}
// Convert to CSV
$a = array_map("str_getcsv", explode(PHP_EOL, $a));
// Get the first part of the array as the keys
$a = [
"keys" => array_shift($a),
"rows" => $a,
"row" => null,
];
// Define JSON
$b = [];
foreach ($a["rows"] as $a["row"]) {
$a["row"] = [ "csv" => $a["row"], "json" => (object)[], ];
for ($c = 0; $c < count($a["row"]["csv"]); $c++) {
$a["row"]["csv"][$c] = [@json_decode($a["row"]["csv"][$c]),$a["row"]["csv"][$c]];
// Switch from string to booleans, numbers and others
$a["row"]["csv"][$c] = isset($a["row"]["csv"][$c][0]) ? $a["row"]["csv"][$c][0] : $a["row"]["csv"][$c][1];
// Push it back
$a["row"]["json"]->{$a["keys"][$c]} = $a["row"]["csv"][$c];
}
$a["row"] = $a["row"]["json"];
$b[] = $a["row"];
unset($a["row"]);
}
// $e will be "return"
$e = $e ? json_encode($b) : $b;
// Unset useless variables
unset($a, $b, $c, $d);
return $e;
}
사용방법?
JSON을 문자열로 반환하려면 기본값으로 둡니다.JSON을 개체/배열로 반환하려면 두 번째 파라미터를 false로 설정합니다.예:
$csv = "name,age,gender
John Doe,35,male
Jane Doe,32,female";
echo csv2json($csv, true); // Or without the second parameter, just csv2json($csv)
( 「 」 。^
는 다음과
[{"name":"John Doe","age":35,"gender":"male"},{"name":"Jane Doe","age":32,"gender":"female"}]
및 다음 예시를 나타냅니다.
var_dump(csv2json($csv, false));
는 다음 오브젝트와 함께 JSON 어레이를 반환합니다.
array(2) {
[0]=>
object(stdClass)#1 (3) {
["name"]=>
string(8) "John Doe"
["age"]=>
int(35)
["gender"]=>
string(4) "male"
}
[1]=>
object(stdClass)#2 (3) {
["name"]=>
string(8) "Jane Doe"
["age"]=>
int(32)
["gender"]=>
string(6) "female"
}
}
public function CsvToJson($fileContent){
//Convert CSV To Json and Return
$all_rows = array();
$newhead =array();
//Extract csv data to array on \n
$array = explode("\n",$fileContent);
//Extract csv header to array on 0 Index
$header = explode(",",$array[0]);
//Remove Header Row From Main Data Array
array_shift($array);
//Extract All Arrays To Saperate Orders
foreach($array as $arr){
$sliced = explode(",",$arr);
array_push($all_rows,$sliced);
}
//Extract All Orders Element To Saperate Array Item
foreach($all_rows as $row){
$sliced = explode(",",$arr);
array_push($all_rows,$sliced);
}
//Remove \r From Header Elements
foreach($header as $key=>$value){
$sliced = str_replace ("\r", "", $value);
array_push($newhead,$sliced);
}
//COMBINE Header as KEY And Row Element As Value
$arrrr = array();
foreach($all_rows as $row) {
//Remove Last Element of ROW if it is \r (Break given in css file for next row)
$count= count($row);
if ($row[$count-1] == "\r") {
array_splice($row, count($row) - 1, 1);
}
//CHECK IF HADER COUNT == ROW COUNT
if (count($header) == count($row)) {
array_push($arrrr,array_combine($newhead,$row));
}
}
//CONVERT ARRAY TO JSON
$json = json_encode($arrrr);
//Remove backslasesh from json key and and value to remove \r
$clean = stripslashes($json);
//CONVERT ARRAY TO JSON AGAIN FOR EXPORT
$jsonagain = json_encode($clean);
return $jsonagain;
}
언급URL : https://stackoverflow.com/questions/28118101/convert-csv-to-json-using-php
'programing' 카테고리의 다른 글
리액트 네이티브로 안드로이드 앱을 만들 수 있나요? (0) | 2023.03.09 |
---|---|
jQuery의 load() 메서드에서 오류를 검출하는 방법 (0) | 2023.03.09 |
반응 – 폼 요소 상태를 형제/부모 요소에 전달하는 올바른 방법? (0) | 2023.03.09 |
AngularJS URL의 모든 슬래시가 %2로 변경되었습니다.f (0) | 2023.03.09 |
리액트 라우터 컴포넌트에 예기치 않은 토큰 < 오류가 있습니다. (0) | 2023.03.09 |