无法将json数据转换为php中的csv

时间:2012-06-19 10:35:28

标签: php jquery json csv

在将数据从JSON转换为CSV格式时,我会在CSV文件中获得如下所示的输出。有什么可能的建议吗?

0,"","","0","0","0","0","","","0","0","","","","0","0","0","0","0","0","","","","","","0","0","0","0","","0","","","0","0","0","","0","0","0","0","0","0","0","","","","","","","","","","","","","","","","","","","","","","","","","","","0","0","","","","","","","","0","0",","",""

我的功能

function csv($form){


$fp = fopen($form, "w");

$sql = "SELECT * FROM log AS jon 
                    LEFT JOIN r as rec ON jon.num=rec.num
                    LEFT JOIN b as bio ON jon.num=bio.num   
                    LEFT JOIN p as po ON jon.num=po.num
                    LEFT JOIN re as recur ON jon.num=recur.num
                    LEFT JOIN s as spir ON jon.num=spir.num
                    LEFT JOIN te as ten ON jon.num=ten.num
                    LEFT JOIN tt as ttai ON jon.num=ttai.num
                    LEFT JOIN vi as vis ON jon.num=vis.num
                    LEFT JOIN ac as acui ON jon.num=acui.num
                    LEFT JOIN au as aud ON jon.num=aud.num
                    LEFT JOIN e as ec ON jon.num=ec.num
                    LEFT JOIN ha as han ON jon.num=han.num
                    LEFT JOIN pe as peri ON jon.num=peri.num
                    LEFT JOIN pr as pre ON jon.num=pre.num";
$res=mysql_query($sql);
if(!$res) die ('Unable to run query:'.mysql_error());


    while ($row = mysql_fetch_assoc($res))
{
    //echo implode(', ', $row)."\r\n";

   fputcsv(STDOUT, $row);
}        

在PHP文件中

$rslt = mysql_query("SELECT * FROM ".$table." WHERE num = ".$id."") or die("Unable to Execute QueryThe error was" . mysql_error());                 
$record = mysql_fetch_assoc($rslt);
var jsonObject = JSON.stringify($record);    

3 个答案:

答案 0 :(得分:2)

还有fputcsv()

$rslt = mysql_query("SELECT * FROM ".$table." WHERE no = ".$id."") or die("Unable to Execute QueryThe error was" . mysql_error());
while ($row = mysql_fetch_assoc($rslt))
{
    fputcsv(STDOUT, $row);
}

此函数负责处理包含逗号的值。

答案 1 :(得分:0)

$rslt = mysql_query("SELECT * FROM ".$table." WHERE no = ".$id."") or die("Unable to Execute QueryThe error was" . mysql_error());
while ($row = mysql_fetch_assoc($rslt))
{
    echo implode(', ', $row)."\r\n";
}

请注意,上述解决方案假设您的字段中没有,

答案 2 :(得分:0)

mysql_connect("localhost","root","");
mysql_select_db("test");
$rslt = mysql_query("SELECT * FROM alok") or die("Unable to Execute QueryThe error was" . mysql_error());                 
$record = mysql_fetch_assoc($rslt);
$jval = json_encode($record);

echo $jval;
database
name(field) ["6","1","1"]
Result
{"name":"[\"6\",\"1\",\"1\"]"}

但您的数据以前是通过json解码格式保存的。