我的当前程序使用python将pdf转换为CSV文件。并使用PHP代码根据JSON文件生成CSV文件。 我想创建另一个csv文件,我可以在其中更改csv文件的标题。
目前我正在使用这些代码获取json文件并下载到csv文件`
<?php
@set_time_limit(0);
ini_set('memory_limit', '256M');
ob_start();
require_once( "../include/core.php" );
require_once( "../include/api_check.php" );
$apiCheck = APICheck();
if ( is_string( $apiCheck ) )
die( $apiCheck );
if ( $apiCheck == false )
if ( !User_IsLoggedIn() )
exit;
$outputType = 'single';
if ( isset( $_REQUEST['output'] ) )
$outputType = $_REQUEST['output'];
$filename = '';
$json = '';
if ( isset( $_POST['data'] ) && User_IsDev() )
{
$filename = 'rawdata.csv';
$json = $_POST['data'];
}
else
{
$id = db::$link->real_escape_string( $_REQUEST['id'] );
$userid = "UserID = '" . User_GetID() . "' AND ";
if ( $apiCheck )
$userid = "";
$query = "SELECT Filename, JSON, DownloadStats FROM uploads WHERE " . $userid . "ID = '" . $id . "'";
$result = db::query( $query );
$row = $result->fetch_row();
$filename = $row[0];
$json = $row[1];
// update download stats
$download_stats = $row[2];
$download_stats = json_decode( $download_stats, true );
$download_stats['lastOutputDownload'] = time();
$download_stats['numOutputDownloads']++;
$download_stats = json_encode( $download_stats );
$download_stats = db::$link->real_escape_string( $download_stats );
$query = "UPDATE uploads SET DownloadStats = '" . $download_stats . "' WHERE UserID = '" . User_GetID() . "' AND ID = '" . $id . "'";
db::query( $query );
}
// parse and serve output
if ( $outputType == 'json' )
{
$json = json_decode( $json, true );
$json = json_encode( $json, JSON_PRETTY_PRINT );
if ( $apiCheck )
header( 'Content-Type: text/plain' );
else
{
$filename = pathinfo( $filename, PATHINFO_FILENAME );
header( 'Content-Description: File Transfer' );
header( 'Content-Type: application/octet-stream' );
header( 'Content-Disposition: attachment; filename="' . $filename . '_output.json"' );
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate' );
header( 'Pragma: public' );
header( 'Content-Length: ' . strlen( $json ) );
}
echo $json;
exit;
}
function format_data( $s = '' )
{
$s = trim( $s );
$s = str_replace( "\n", ' ', $s );
$s = str_replace( ',', ' ', $s );
return $s;
}
$json = json_decode( $json, true );
// metadata legend
$csv .= "KEY,VALUE\r\n";
// metadata csv
foreach ( $json['metaData'] as $key => $data )
{
$csv .= format_data( $key ) . ",";
$text = format_data( $data );
if ( empty( $text ) )
$text = 'not in invoice';
$csv .= $text . "\r\n";
}
// splitter
$csv .= "\r\n================\r\n\r\n";
// entry legend, default values
$default_values = array( 'name', 'value' );
foreach ( $default_values as $key )
$csv .= strtoupper( format_data( $key ) ) . ",";
// entry legend, keys in json
$keyCache = array();
foreach ( $json['entries'] as $entry )
// print_r($json['entries']);
foreach ( $entry as $key => $data )
if ( !in_array( $key, $keyCache ) )
$keyCache[] = $key;
foreach ( $keyCache as $key )
if ( !in_array( $key, $default_values ) )
$csv .= strtoupper( format_data( $key ) ) . ",";
$csv = substr( $csv, 0, -1 );
$csv .= "\r\n";
// convert entries
foreach ( $json['entries'] as $entry )
{
// print_r($json['entries']);
foreach ( $default_values as $dk )
$csv .= format_data( $entry[$dk] ) . ",";
foreach ( $keyCache as $key )
{
// print_r($key);
$value = $entry[$key];
if ( !in_array( $key, $default_values ) )
$csv .= format_data( $value ) . ",";
}
$csv = substr( $csv, 0, -1 );
$csv .= "\r\n";
}
// free some ram
unset( $json );
// re parse if single part
if ( $outputType == 'single' )
{
$split = explode( '================', $csv );
$csv = '';
$metadata = str_getcsv( trim( $split[0] ), "\n" );
foreach( $metadata as &$row ) $row = str_getcsv( $row );
array_shift( $metadata );
$entries = str_getcsv( trim( $split[1] ), "\n" );
foreach( $entries as &$row ) $row = str_getcsv( $row );
// free some ram
unset( $split );
// generate metadata legend
$legend_metadata = '';
foreach ( $metadata as $mrow )
$legend_metadata .= $mrow[0] . ',';
$legend_metadata = substr( $legend_metadata, 0, -1 );
// generate metadata values
$metadata_values = '';
foreach ( $metadata as $mrow )
$metadata_values .= $mrow[1] . ',';
$metadata_values = substr( $metadata_values, 0, -1 );
// generate entry legend
$legend_entries = '';
foreach ( $entries[0] as $key )
$legend_entries .= $key . ',';
$legend_entries = substr( $legend_entries, 0, -1 );
array_shift( $entries );
// generate csv
$csv .= $legend_entries;
$csv .= ',';
$csv .= $legend_metadata;
$csv .= "\r\n";
foreach ( $entries as $erow )
{
$row_csv = '';
foreach ( $erow as $val )
$row_csv .= $val . ',';
$row_csv .= $metadata_values;
$csv .= $row_csv;
$csv .= "\r\n";
}
}
// output file
$filename = pathinfo( $filename, PATHINFO_FILENAME );
if ( $apiCheck )
{
header( 'Content-Type: text/plain' );
}
else
{
header( 'Content-Description: File Transfer' );
header( 'Content-Type: application/octet-stream' );
header( 'Content-Disposition: attachment; filename="' . $filename . '_output.csv"' );
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate' );
header( 'Pragma: public' );
header( 'Content-Length: ' . strlen( $csv ) );
}
echo $csv;
?>
`
答案 0 :(得分:0)
json_data="""[{'Fname':'Ashu', 'Lname':'Dagar', 'Phone':'1234567890'}]"""
import csv
import json
data = json.loads(json_data)
f = csv.writer(open("test.csv", "wb+"))
#writing specific header to csv
f.writerow(['Fname','Lname'])
#write data to csv
for value in data:
f.writerow([value["Fname"], value["Lname"]])
you will get output as :
Fname,Lname
Ashu,Dagar
如果您的json中丢失了键,那么您可以定义自己的dict,它在csv中充当标头,并从json中获取您在dict中定义的相同键的值,从而为您提供数据。