我想将以下可工作的代码转换为PDO,但我遇到了在 fputcsv($output,array)
中设定自定义标题的问题。我真的想远离所有mysql_函数,所以非常希望得到一些帮助。
<?php
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=collections.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
//MySQL Connect
removed
// output the column headings
fputcsv($output, array('Title','InclusiveDates','CollectionID','LocationID','Content','RangeValue','Section','Shelf','Extent','ExtentUnitID'));
// fetch the data
$rows = mysql_query('SELECT
coll.title AS CollectionTitle,
coll.inclusivedates AS InclusiveDates,
coll.ID AS CollectionID,
collloc.LocationID,
collloc.Content,
collloc.RangeValue,
collloc.Section,
collloc.Shelf,
collloc.Extent,
collloc.ExtentUnitID
FROM tblCollections_Collections coll
JOIN tblCollections_CollectionLocationIndex collloc
ON collloc.CollectionID = coll.id
ORDER BY coll.ID');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
?>
我已经做到了这一步,但仍无法使其正常工作。问题在于我无法设置CSV文件中的自定义列名,并且它也不能导出为CSV格式。
<?php
$conn = removed
$query = "SELECT
coll.title AS CollectionTitle,
coll.inclusivedates AS InclusiveDates,
coll.ID AS CollectionID,
collloc.LocationID,
collloc.Content,
collloc.RangeValue,
collloc.Section,
collloc.Shelf,
collloc.Extent,
collloc.ExtentUnitID
FROM tblCollections_Collections coll
JOIN tblCollections_CollectionLocationIndex collloc
ON collloc.CollectionID = coll.id
ORDER BY coll.ID";
$stmt = $conn->prepare($query);
// Execute the statement
$stmt->execute();
var_dump($stmt->fetch(PDO::FETCH_ASSOC));
$data = fopen('file.csv', 'w');
$header = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if(empty($header)){ // do it only once!
$header = array_keys($row); // get the columnnames
fputcsv($data, $header); // put them in csv
}
echo "Success";
// Export every row to a file
fputcsv($data, $row);
}
?>
fclose
函数关闭文件吗? - Mattprepare()
。 - david strachan