[英]I am exporting data from table convert to CSV, to JavaScript variable. . But getting Error "fputcsv() expects parameter 2 to be array" . How to do it?
This is my PHP code这是我的 PHP 代码
<?php
require_once 'd:\xampp\htdocs\bpr\pdo_db.php';
$sql = "Select ID,FULL_NAMe,AGE from TRIAL";
$csv = get_csv_string($dbh, $sql);
echo "<script> var_csv='" . $csv . "' </script>";
function get_csv_string($dbh, $sql)
{
try
{
$result = $dbh->query($sql);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
if ($row == null) {
return "No Data";
}
$f = fopen('php://memory', 'r+');
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
//second query gets the data
$data = $dbh->query($sql);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach ($data as $row) {
if (fputcsv($f, $row) === false) {
return false;
}
} // end record loop
rewind($f);
$csv = stream_get_contents($f);
return rtrim($csv);
} catch (PDOExepction $e) {
return $e->getMessage();
}
return $csv;
}
I am getting following error!我收到以下错误!
Instead of fputcsv(), I made my own code.我自己编写了代码,而不是 fputcsv()。 But issue if found when I save the CSV to a javascript variable.
但是如果在我将 CSV 保存到 javascript 变量时发现问题。 Is there any other way to convert the data to CSV and pass it on to javascript?
有没有其他方法可以将数据转换为 CSV 并将其传递给 javascript? I will convert this csv to JSON at Client side using javascript
我将使用 javascript 在客户端将此 csv 转换为 JSON
You're trying to output a header row to CSV with the field names.您正在尝试使用字段名称将标题行输出到 CSV。
This code fails because you're looping through the $row
array and attempting to write one field header at a time.此代码失败,因为您正在遍历
$row
数组并尝试一次写入一个字段标题。
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
What you want is an array with the field names in it.你想要的是一个包含字段名称的数组。 You can use
array_keys()
for that, so your code becomes您可以为此使用
array_keys()
,因此您的代码变为
if (fputcsv($f, array_keys($row)) === false) return false;
No loop required.不需要循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.