格式化php生成的csv文件

时间:2013-02-03 11:14:13

标签: php csv

我编写了一个将mysql数据转换为csv文件的代码。问题是它将结果水平显示为

DATE        AUTHOR  LIKES   COMMENTS`
1/31/2013   WTF Facts   211 3
1/31/2013   WTF Facts   211 23
1/31/2013   WTF Facts   211 23
1/31/2013   WTF Facts   211 23
1/31/2013   WTF Facts   211 23

DATE        AUTHOR  LIKES   COMMENTS`
1/31/2013   WTF Facts   211 3
1/31/2013   WTF Facts   211 23
1/31/2013   WTF Facts   211 23
1/31/2013   WTF Facts   211 23
1/31/2013   WTF Facts   211 23

然而我想垂直地想要它

DATE        AUTHOR  LIKES   COMMENTS`   DATE    AUTHOR     LIKES    COMMENTS`
1/31/2013   WTF Facts   211 3           1/31/2013   WTF Facts  211      23
1/31/2013   WTF Facts   211 23          1/31/2013   WTF Facts  211      23
1/31/2013   WTF Facts   211 23          1/31/2013   WTF Facts  211      3
1/31/2013   WTF Facts   211 23          1/31/2013   WTF Facts  211      23
1/31/2013   WTF Facts   211 23          1/31/2013   WTF Facts  211      23

这是我的代码:

      <?php
      if(isset($_POST['submit'])):
        set_time_limit(99999999);
        ini_set('memory_limit', "9999M");
        $filename_csv = "export_".rand(1000000,9999999)."_".rand(1000000,9999999).".csv";
        $path = "serp_csvs_page/".$filename_csv;
        $fp = fopen($path, 'w');
        $page_ids = $_POST['page_id'];
        $date_from =  $_POST['date_from'];
        $date_to = $_POST['date_to'];

        foreach($page_ids as $page_id):
            $brline = array("\n");
            $page_name = get_page_name_by_id($page_id);
            $dates = checkCsvQuotes("DATE: FROM {$date_from} TO {$date_to}") ;
            $page_name = checkCsvQuotes("PAGE ID: {$page_name['page_id']}");
            $header = array($dates, "\n", $page_name);
            fputcsv($fp, $header);
            fputcsv($fp, $brline);
            $query = sprintf("SELECT post_date AS `DATE`, post_from AS `AUTHOR`, message AS `MESSAGE`, total_likes AS `TOTAL LIKES`, total_comments AS `TOTAL COMMENTS` FROM tbl_contents_pages WHERE `pid_id` = '$page_id' AND `post_date` >= '$date_from' AND `post_date` <= '$date_to'");
            $result = mysql_query($query, $con) or die(mysql_error($con));
            $rows = mysql_fetch_assoc($result);
            if ($rows) {
                $arr_key = array_keys($rows); 
                fputcsv($fp, $arr_key);
                while($rows = mysql_fetch_assoc($result))
                {
                    $date_row = checkCsvQuotes($rows['DATE']);
                    $author_row = checkCsvQuotes($rows['AUTHOR']);
                    $message_row = checkCsvQuotes($rows['MESSAGE']);
                    $likes_row = checkCsvQuotes($rows['TOTAL LIKES']);
                    $comments_row = checkCsvQuotes($rows['TOTAL COMMENTS']);
                    $arr_value = array();
                    $arr_value[] = $date_row;
                    $arr_value[] = $author_row;
                    $arr_value[] = $message_row;
                    $arr_value[] = $likes_row;
                    $arr_value[] = $comments_row;
                    //print_r($arr_value);
                    fputcsv($fp, $arr_value);
                }
            }
            else
            {
                $noData = array("DO RECORDS FOUND.");
                fputcsv($fp, $noData);
            }
            fputcsv($fp, $brline);
        endforeach;
        fclose($fp);
        echo "<a href=serp_csvs_page/".$filename_csv." class='btn btn-primary'> View File </a>";  
        endif;
      function get_page_name_by_id($id)
        {
            $query = mysql_query("SELECT page_id FROM tbl_pages WHERE `id` = '$id'");
            $result = mysql_fetch_assoc($query);
            return $result;
        }
    function checkCsvQuotes($string) 
    {
        if (strpos($string,'"') !== false) {
            return '"'.str_replace('"','""',$string).'"';
        } elseif (strpos($string,',') !== false) {
            return '"'.$string.'"';
        } else {
            return $string;
        }
    }
      ?>

我不确定即使它可能,因为我是新的csv。如果你们有任何想法并且与我相处,我将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

你需要继续扩展数组,而不是立即吐出元素。我已经改变了你的代码,但由于我无法测试它,它很可能无法正常工作。无论哪种方式,比较代码以了解需要做什么。

<?php
if(isset($_POST['submit'])):
    set_time_limit(99999999);
    ini_set('memory_limit', "9999M");
    $filename_csv = "export_".rand(1000000,9999999)."_".rand(1000000,9999999).".csv";
    $path = "serp_csvs_page/".$filename_csv;
    $fp = fopen($path, 'w');
    $page_ids = $_POST['page_id'];
    $date_from =  $_POST['date_from'];
    $date_to = $_POST['date_to'];

    $data_ar = array(); //create a "master" array
    $i = $j = 0;

    foreach($page_ids as $page_id):
        $brline = array("\n");
        $page_name = get_page_name_by_id($page_id);
        $dates = checkCsvQuotes("DATE: FROM {$date_from} TO {$date_to}") ;
        $page_name = checkCsvQuotes("PAGE ID: {$page_name['page_id']}");
        $header = array($dates, "\n", $page_name);
        fputcsv($fp, $header);
        fputcsv($fp, $brline);
        $query = sprintf("SELECT post_date AS `DATE`, post_from AS `AUTHOR`, message AS `MESSAGE`, total_likes AS `TOTAL LIKES`, total_comments AS `TOTAL COMMENTS` FROM tbl_contents_pages WHERE `pid_id` = '$page_id' AND `post_date` >= '$date_from' AND `post_date` <= '$date_to'");
        $result = mysql_query($query, $con) or die(mysql_error($con));
        $rows = mysql_fetch_assoc($result);
        if ($rows) {
            $arr_key = array_keys($rows); 
            fputcsv($fp, $arr_key);
            $i = 0; //set to 0 on each iteration over $page_ids
            while($rows = mysql_fetch_assoc($result))
            {
                $date_row = checkCsvQuotes($rows['DATE']);
                $author_row = checkCsvQuotes($rows['AUTHOR']);
                $message_row = checkCsvQuotes($rows['MESSAGE']);
                $likes_row = checkCsvQuotes($rows['TOTAL LIKES']);
                $comments_row = checkCsvQuotes($rows['TOTAL COMMENTS']);
                if ($j === 0) //note: this assumes all files have the same amount of data
                    $data_ar[$i] = array();
                $data_ar[$i][] = $date_row; //these will add to array data instead of creating new array rows
                $data_ar[$i][] = $author_row;
                $data_ar[$i][] = $message_row;
                $data_ar[$i][] = $likes_row;
                $data_ar[$i][] = $comments_row;
                //print_r($arr_value);
                $i++;
            }
        }
        else
        {
            $noData = array("DO RECORDS FOUND.");
            fputcsv($fp, $noData);
        }
        $j++;
    endforeach;
    for ($q = 0; $q < count($data_ar); $q++) { //insert data to file once the data has been gathered
        fputcsv($fp, $data_ar[$q]);
        fputcsv($fp, $brline);
    }
    fclose($fp);
    echo "<a href=serp_csvs_page/".$filename_csv." class='btn btn-primary'> View File </a>";  
    endif;
?>