質問

I try to create a csv file with selected rows from a mssql database. The export works but the formatting is wrong.

PHP:

require_once("config/config.php");

$connectionInfo = array("Database"=>DB_DB, "UID"=>DB_USER, "PWD"=>DB_PASSWORD);
$conn = sqlsrv_connect(DB_HOST, $connectionInfo);

if ($conn === false ) {
    die (print_r(sqlsrv_errors(), true));
}

$sql = "SELECT * FROM [RC.Appointments]";
$result = sqlsrv_query($conn, $sql);

if (!$result) die ('Couldn\'t fetch records');

$headers = array();

foreach (sqlsrv_field_metadata($result) as $fieldMetadata) {
    $headers[] = $fieldMetadata['Name'];
}

$fp = fopen('php://output', 'w');
if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');
    fputcsv($fp, $headers);
    while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC)) {
        fputcsv($fp, array_values($row));
    }
    die;
}

Dont know why there are no headers and I need the data seperate by columns. Is the problem caused by the missing headers?

the output in sublimetext

appointment_id,terminname,datum
151,"Bitte Terminnamen vergeben",18.02.2014
152,"Bitte Terminnamen vergeben",19.02.2014
153,"Bitte Terminnamen vergeben",20.02.2014
154,"Bitte Terminnamen vergeben",25.02.2014
155,"Bitte Terminnamen vergeben",26.02.2014
156,"Bitte Terminnamen vergeben",27.02.2014
157,"Bitte Terminnamen vergeben",31.12.2014
役に立ちましたか?

解決

As from the second output with sublimetext, the $headers array doesn't contain anything.

So the statement $headers[] = sqlsrv_get_field($result , $i); needs to be checked.

As it's furthermore dumping the array instead of printing it, I would try: fputcsv($fp, array_values($headers));

In order to get this interpreted by Excel properly, change the delimiter to ;: fputcsv($fp, array_values($headers), ';');

他のヒント

The problem is that sqlsrv_get_field() returns the data in the current field and not the name and it has to be setup to use the correct index by calling sqlsrv_fetch(). But this is not what you want to do. What you need to do is to get the headers which can be done like this:

foreach( sqlsrv_field_metadata($result) as $fieldMetadata)
{
    $headers[] = $fieldMetadata['Name'];
}

and as been already pointed out by Alex the correct way to write the headers to the csv file is:

fputcsv($fp, array_values($headers));

Now as for the way the file is displayed in Excel you can import the file using the Text import Wizard explained here

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top