2017-10-02 22 views
0

私が.phpファイルを持っていて、元のファイルを変更せずに新しい行のコードを挿入したいとします。コードをfile_put_contentsで.phpファイルに挿入

例:私はfile_put_contentsと任意のコードを挿入したい行3と4の間

require_once 'includes/application_top.php'; 
$smarty = new Smarty; 
require DIR_FS_CATALOG . 'templates/' . CURRENT_TEMPLATE . '/source/boxes.php'; 
include DIR_WS_MODULES . 'default.php'; 
require DIR_WS_INCLUDES . 'header.php'; 
$smarty->assign('language', $_SESSION['language']); 

file_get_contentsでファイルを読み取り、任意のコードを挿入できますか?

+0

は、()ステートメントを試しため、これは便利であると思います。 – Blaise

+0

あなたは何をしようとしているのか分かりません。 'file_put_contents'を使うと元のファイルを修正します。 – Barmar

+1

私はあなたが望むものを達成するためのより良い方法があると確信しています。条件付きロジックなどを使用できますか? – dan08

答えて

0

私が正しくあなたの質問を理解している場合は、外部ファイルにPHPコードを持っていて、別のPHPコードを使用して、その内容に新しい行を追加したい、それが正しい場合は、次のコードを使用することができます。

<?php 
 

 
$content = file_get_content("a.php"); 
 

 
function add_new_line($content, $insert_code, $line_number){ 
 
\t $lines = explode("\n", $content); 
 
\t $segment_1 = array_slice($lines, 0, $line_number); 
 
\t $segment_2 = array_slice($lines, $line_number, count($lines) - 1); 
 
\t array_push($segment_1, $insert_code); 
 
\t $lines = array_merge($segment_1, $segment_2); 
 
\t return $str = implode("\n", $lines); 
 
} 
 

 

 
$line_number = 3; 
 
$insert_code = "echo 'this is new line';"; 
 

 
// add new line of code to the content 
 
$new_content = add_new_line($content, $insert_code, $line_number); 
 

 
// insert new file content: 
 
file_put_content("a.php", $new_content);

私はあなた

+0

これは、ファイルに対して一度だけ実行される何らかのジョブであれば意味があります。ユーザーがプライベートURLを使用するのではなくページにアクセスしたときにこのコードを実行すると、a.phpは余分なコードを繰り返し追加します。 –

関連する問題