Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 当我们将json文件转换为python时,是否可以将自定义标题创建为csv文件_Php_Python - Fatal编程技术网

Php 当我们将json文件转换为python时,是否可以将自定义标题创建为csv文件

Php 当我们将json文件转换为python时,是否可以将自定义标题创建为csv文件,php,python,Php,Python,我当前的程序使用python将pdf转换为CSV文件。CSV文件是使用php代码根据JSON文件生成的。 我想创建另一个csv文件,在其中我可以更改csv文件的标题 目前我正在使用这些代码获取json文件并下载到csv文件中` <?php @set_time_limit(0); ini_set('memory_limit', '256M'); ob_start(); require_once( "../include/core.php" ); require_once( "../inc

我当前的程序使用python将pdf转换为CSV文件。CSV文件是使用php代码根据JSON文件生成的。 我想创建另一个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;

?>


`是的,你能做到。但是首先不要把你的php代码和python的要求。其次,不要复制应用程序的全部代码,粘贴相关代码。向我们展示你做了什么,以及你在哪里遇到了困难或面临的问题。 下面是一个简单的示例,用于使用特定标题从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中丢失了密钥,那么您可以定义自己的dict,它在csv中充当头文件,并从json中获取dict中定义的相同密钥的值,这将为您提供数据。

是否有任何更新?是的,我们可以。。给你。。现在你可以将问题标记为已回答…这里有一个很棒的页面,包含许多好信息:阅读链接并尝试发布一个符合这些指导原则的问题。。。你需要具体一点,你需要向我们展示相关的代码,哪里有问题,你尝试了什么。你现在的问题是“我们能……吗”,我实际上已经回答了。除此之外,不可能了解您的问题所在……好的,谢谢您的更新。实际上,我想在csv文件中实现自定义标题,而我只有json文件。所以,你能给我一些有用的代码或链接吗