php
  • fwrite
  • file-put-contents
  • 2017-04-10 82 views -1 likes 
    -1

    我想從apriori_main表中取一些整數,並將它們作爲逗號分隔值存儲到文本文件中。對於每次迭代,我使用file_put_contents在下一行寫入數據。使用fwrite給出了相同的結果。追加到文件,而不使用PHP添加換行符

    我想在文本文件中的輸出是:

    1,2,3,4 
    

    但我得到的輸出是:

    1 
    ,2 
    ,3 
    ,4 
    

    這裏是代碼片段:

    $y=""; 
    $stmt='SELECT category FROM apriori_main where id='.$id.''; 
    $nRows = $conn->query('select count(category) from apriori_main where id='.$id.'')->fetchColumn(); 
    echo $nRows; 
    
    $file = "/opt/lampp/htdocs/ghi.txt"; 
    $f = fopen($file, 'a+'); // Open in write mode 
    $count=1; 
    
    foreach($conn->query($stmt) as $row) 
    { 
        if($count!=$nRows) 
        { 
         $user = $row['category']."\n"; 
         $y=$user; $y=$y.","; 
         $str=$y; echo $y; 
         $count=$count+1; 
        } 
        else 
        { 
         $user = $row['category']."\n"; 
         $y=$user; $str=$y; echo $y; 
        } 
        file_put_contents($file, $str, FILE_APPEND); 
    } 
    fclose($f); 
    
    +2

    嗯......'。 「\ n」'爲什麼? – AbraCadaver

    +0

    \ n等於換行,所以你要讓它在新行上開始 –

    +1

    如果你打算使用'file_put_contents',你實際上不需要打開文件句柄。 –

    回答

    -1

    我不知道你對這些值做了什麼,但你似乎有很多不必要的變量聲明。

    我認爲你可以有效地打破了這一切

    $file = "/opt/lampp/htdocs/ghi.txt"; 
         $f = fopen($file, 'a+'); // Open in write mode 
         $count=1; 
    
    
         foreach($conn->query($stmt) as $row) 
         { 
         if($count!=$nRows) 
         { 
          $user = $row['category']."\n"; 
          $y=$user; $y=$y.","; 
          $str=$y; echo $y; 
          $count=$count+1; 
         } 
         else 
         { 
          $user = $row['category']."\n"; 
          $y=$user; $str=$y; echo $y; 
         } 
         file_put_contents($file, $str, FILE_APPEND); 
        } 
         fclose($f); 
    

    下到這個(在末尾只有一個文件操作)

    $file = "/opt/lampp/htdocs/ghi.txt"; 
    
    foreach($conn->query($stmt) as $row) 
    { 
        $y[] = $row['category']; 
    } 
    //output to screen 
    echo implode("<br>", $y); 
    //output to file 
    file_put_contents($file,implode(",", $y)); 
    
    +0

    非常感謝您在短時間內解決我的問題。 – user3379583

    0

    這就是所需要的全部:

    $stmt = 'SELECT category FROM apriori_main where id='.$id.''; 
    $file = "/opt/lampp/htdocs/ghi.txt"; 
    
    foreach($conn->query($stmt) as $row) 
    { 
        $str[] = $row['category']; 
    } 
    file_put_contents($file, implode(',', $str)); 
    // only use FILE_APPEND if needed for the next time to append 
    
    • 通過查詢結果行
    • 追加category到一個數組
    • 破滅數組元素之間用逗號,和寫入文件循環

    因此,在短期,您:

    1. 不需要查詢計數
    2. 不需要打開文件
    3. 不要使用\n這是一個換行符
    4. 不需要加逗號,在循環
    5. 不要寫每次循環迭代
    +0

    非常感謝您在短時間內解決我的問題。它非常完美! – user3379583

    相關問題