代码之家  ›  专栏  ›  技术社区  ›  Rory Perry

在MySQL中存储\r\n并通过PHP检索和写入文本文件

  •  1
  • Rory Perry  · 技术社区  · 7 年前

    我有一个数据集,需要通过CSV导入到应用程序中。我遇到的问题是程序用来表示新行的字符没有被导出。

    MySQL识别出它们在数据库中,但PHP似乎无法将它们导出到文本文件中,而是执行它们。有人能给我指出正确的方向吗?我有点迷路了。

    变量:

    $elec_desc = "Value Used " . $row['item_no'] . " From " . date('d-m-Y', strtotime($readings[3])) . " to " . date('d-m-Y', strtotime($readings[1])) . '\\r\\n' . "Prev Reading " . $readings[2] . " QTY Type    New Reading " . $readings[0] . " QTY Type " . '\\r\\n' . "Total Usage " . $totalused . " QTY Type " . '\\r\\n' . "Price per QTY Type \$$usagefee";
    

    目前还没有使用准备好的语句,我计划在一切正常后再进行修改。

    导出:

            if ($res[$price] != 0.00){
                $string_to_push = $res['inv_no'] . "," . $res['inv_date'] . "," . $sres['name'] . "," . $res[$acc] . "," . $res[$desc] . "," . $res[$gst] . "," . round((($res[$price]/11)*10),2) . "," . round(($res[$price]/11),2) . ",E";
                array_push($array_of_invs, $string_to_push);
    
            } else {
                $i = 11;
            }
        }
    }
    
    $prevsub = "IV000000";
    
    for($inc=0;$inc<sizeof($array_of_invs);$inc++){
        $file_name = $curr_date . "_inv_export.txt";
        $string = $array_of_invs[$inc];
    
        if ($prevsub == substr($string,0,8)){
            $myfile = file_put_contents($file_name, $string.PHP_EOL , FILE_APPEND | LOCK_EX);
        } else {
            $myfile = file_put_contents($file_name, PHP_EOL, FILE_APPEND | LOCK_EX);
            $myfile = file_put_contents($file_name, ($string.PHP_EOL) , FILE_APPEND | LOCK_EX);
        }
    
        $prevsub = substr($string,0,8);
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Rory Perry    7 年前

    看来解决办法很简单。只对它们进行一次转义是不够的,因为它们包含在一个变量中,答案是对它们进行两次转义。我从来没有想过要走这条路,因为我认为在上面加上第三条斜线只会执行它们。

     \\\r\\\n 
    

    ^似乎做到了这一点,因为它们在MySQL中正确存储并正确导出。