PHP fwrite选项卡分隔的文本文件不正确

时间:2012-08-23 22:15:08

标签: php mysql csv fwrite

我正在尝试编写制表符分隔的文本文件。其中一个字段是产品描述,其中包含HTML并导致问题(我测试过没有,它工作正常)。在第95行,结构破裂。我已经检查了第95行的字段,它是纯文本(没有中断或标签)。

导致文件混乱的东西。我尝试了trim,strip_tags,utf8_encode,删除了多个空格,并通过“/ n”(然后内爆)将字符串拼接成数组。

我的代码:

///////////// Get product data from database and store as array /////////////

$products = array();
$c=0;

    $fprod = mysql_query("SELECT id,name,desc FROM products");
    while ($sprod = mysql_fetch_array($fprod)) {

    $products[$c]["id"] = trim($sprod["id"]);
    $products[$c]["name"] = trim($sprod["name"]);

    // strip product description field (the part that doesn't work)

        $prod_desc_a = utf8_encode(strip_tags($sprod["desc"]));    

        // convert any breaks or tabs to \n, explode by \n and then implode

        $prod_desc_b = str_replace(array("\r\n", "\r", "\t", " \t "), "\n", $prod_desc_a);
        $lines = explode("\n", $prod_desc_b);
        $new_lines = array(); 

        foreach ($lines as $i => $line) {
        if(!empty($line))
        $new_lines[] = trim($line);
        }

    $prod_desc_c = implode($new_lines);

// finally remove any multiple spaces and store in array

$prod_desc_final = preg_replace('/\s+/', ' ',$prod_desc_c);


$products[$c]["desc"] = $prod_desc_final;

$c++;
}


///////////// Write the file /////////////

$myFile = "feeds/froogle.txt";
$fh = fopen($myFile, 'w');

    $newline= " \n ";
    $tab= " \t ";

    foreach ($products as $product) {
    $this_line = $product[id] . $tab. $product[name] . $tab . $product[desc] . PHP_EOL; 
    fwrite($fh, $this_line);     
    $this_line = '';
    }

fclose($fh);

我导入Excel或Google文档时文件中断的任何想法?非常感谢。

0 个答案:

没有答案