2016-11-08 56 views
-1

我當前的程序使用python將pdf轉換爲CSV文件。並根據使用php代碼的JSON文件生成CSV文件。 我想創建另一個csv文件,我可以在其中更改csv文件的標題。當我們將json文件轉換爲python時,我們可以創建自定義標題到csv文件中

目前我使用這些代碼來獲得JSON文件並下載到CSV file`

<?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

是的,我們可以..你去那裏..現在你可以將問題標記爲已回答... –

+0

以下是一個很棒的信息:http://stackoverflow.com/help/how-to-ask –

回答

0

是你可以做的。但首先不要把你的PHP代碼,並要求蟒蛇。其次,不要複製你的應用程序的整個代碼,粘貼相關的代碼。告訴我們你做了什麼以及你遇到問題或遇到問題。 對於做JSON來CSV低於特定頭是簡單的例子:

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鍵,那麼你可以定義自己的字典,其充當CSV頭,並從獲得的值你在dict中定義的相同鍵的json,它給你提供了數據。

+0

謝謝,它的工作原理 –

相關問題