格式化php创建的CSV文件(顶行标题,第二行数据)

时间:2011-03-10 23:32:42

标签: php sql csv formatting export

header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"yourfile.csv\"");

我用它来制作CSV文件;

目前它正在显示数据为

标题,数据,标题2,数据2,标题3,数据3 ......

我想将数据显示为;

标题,标题2,标题3
数据1,数据2,数据3

如何做到这一点?

    <?php
$sql = "SELECT * FROM survey
        WHERE id = '".sql_escape($s)."'";
$row = fetch0ne($sql);

if(!empty($row)) {

    $int = array();

    $sql = "SELECT * FROM survey_interests
            WHERE survey = '".sql_escape($s)."'";
    $interests = fetchAll($sql);

    if(!empty($interests)) {
        foreach($interests as $item) {
            $int[] = getInterest($item['interest']);
        }
    }


header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"yourfile.csv\"");   
?>
Full Name, <?php echo $row['first_name']." ".$row['last_name']; ?>, Age, <?php echo $row['age']; ?>, Gender, <?php echo $row['gender'] == 'm' ? 'Male' : 'Female'; ?>, Country, <?php echo getCountry($row['country']); ?>, <?php if(!empty($int)) { ?><?php echo implode(", ",$int); ?><?php } ?>, Favorite colour, <?php echo getColour($row['colour']); ?>, Favorite search engine, <?php echo getSearchEngines($row['search_engine']); ?>

<?php

}
?>

2 个答案:

答案 0 :(得分:1)

你可以改变你的代码:

<?php
$sql = "SELECT * FROM survey
        WHERE id = '".sql_escape($s)."'";
$row = fetch0ne($sql);

if(!empty($row)) {

    $int = array();

    $sql = "SELECT * FROM survey_interests
            WHERE survey = '".sql_escape($s)."'";
    $interests = fetchAll($sql);

    if(!empty($interests)) {
        foreach($interests as $item) {
            $int[] = getInterest($item['interest']);
        }
    }


header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"yourfile.csv\"");   
?>
Full Name, Age, Gender, Country, Favorite colour, Favorite search engine
<?php echo $row['first_name']." ".$row['last_name']; ?>, <?php echo $row['age']; ?>, <?php echo $row['gender'] == 'm' ? 'Male' : 'Female'; ?>, <?php echo getCountry($row['country']); ?>, <?php echo getColour($row['colour']); ?>, <?php echo getSearchEngines($row['search_engine']); ?>

<?php

}
?>

答案 1 :(得分:0)

我认为你的数据就像是吼叫 -

$records = array(
               [0] = array(heading=>data 1, heading 2=>data 2, heading 3=>data 3),
               [1] = array(heading=>data 1, heading 2=>data 2, heading 3=>data 3),
               [2] = array(heading=>data 1, heading 2=>data 2, heading 3=>data 3),
               [3] = array(heading=>data 1, heading 2=>data 2, heading 3=>data 3)
           );

您可以遵循以下概念 -

$heading = implode(',', array_keys( array_pop($records) ) );

header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"yourfile.csv\"");

echo $heading."\n\r"; // HEADER IS BEING PLACED HERE

foreach($records as $row){ // CONTENTS IS BEING PLACED HERE
    echo implode(',', $row)."\n\r";
}
exit;