2014-11-19 1 views
2

다음 텍스트 파일과 PHP 코드가 있습니다. 텍스트 파일에는 몇 가지 부수적 인 변수가 있고 양식의 특정 변수를 업데이트하고 싶습니다. .파일의 나머지 부분을 보존하면서 PHP를 사용하여 텍스트 파일의 특정 줄 바꾸기

문제는 제출시 코드가 실행될 때 텍스트 파일에 변수가 올바르게 읽히지 않도록 텍스트 파일에 줄을 추가하는 것입니다. 텍스트 파일, 코드 및 결과를 아래에 추가했습니다.

텍스트 파일 :

Title 
Headline 
Subheadline 
extra 1 
extra 2 

PHP 코드 : 편집 후

<?php 
session_start(); 
// Get text file contents as array of lines 
$filepath = '../path/file.txt'; 
$txt = file($filepath); 
// Check post 
if (isset($_POST["input"]) && 
    isset($_POST["hidden"])) { 
    // Line to edit is hidden input 
    $line = $_POST['hidden']; 
    $update = $_POST['input']; 
    // Make the change to line in array 
    $txt[$line] = $update; 
    // Put the lines back together, and write back into text file 
    file_put_contents($filepath, implode("\n", $txt)); 
    //success code 
    echo 'success'; 
} else { 
    echo 'error'; 
} 
?> 

텍스트 파일 :

Title edited 
Headline 

Subheadline 

extra 1 

extra 2 

원하는 결과 :

Title edited 
Headline 
Subheadline 
extra 1 
extra 2 
+2

$의 txt''의 모든 원래의 요소는 이미 새로운 라인의 기호가로'내파 ("", $의 TXT)' 결국. 자신이 삽입하는 요소에 추가하기 만하면됩니다. '$ txt [$ line] = $ update. "\ n"(각 경우에 따라 다름) – Cheery

+0

@Cheery 완벽하게 작동했습니다. 감사합니다. – Alex

+1

str_replace를 사용하면 훨씬 빠릅니다. –

답변

3

는 명랑하고 다곤 두 솔루션 덕분에 있습니다.

해결 방법 1

<?php 
session_start(); 
// Get text file contents as array of lines 
$filepath = '../path/file.txt'; 
$txt = file($filepath); 
//check post 
if (isset($_POST["input"]) && 
    isset($_POST["hidden"])) { 
    $line = $_POST['hidden']; 
    $update = $_POST['input'] . "\n"; 
    // Make the change to line in array 
    $txt[$line] = $update; 
    // Put the lines back together, and write back into txt file 
    file_put_contents($filepath, implode("", $txt)); 
    //success code 
    echo 'success'; 
} else { 
    echo 'error'; 
} 
?> 

해결 방법 2

<?php 
session_start(); 
// Get text file contents as array of lines 
$filepath = '../path/file.txt'; 
$txt = file($filepath); 
// Get file contents as string 
$content = file_get_contents($filepath); 
//check post 
if (isset($_POST["input"]) && 
    isset($_POST["hidden"])) { 
    $line = $_POST['hidden']; 
    $update = $_POST['input'] . "\n"; 
    // Replace initial string (from $txt array) with $update in $content 
    $newcontent = str_replace($txt[$line], $update, $content); 
    file_put_contents($filepath, $newcontent); 
    //success code 
    echo 'success'; 
} else { 
    echo 'error'; 
} 
?> 
관련 문제