Mohamed Omar Mohamed Omar - 10 days ago 5
PHP Question

Can i export a specific lines from file to another?

If have a file

A.php
which for sure have some lines, and i want to export or copy specific lines from
A.php
to a new file
B.php
, So the process goes like this (copy lines from x to y in the
A.php
- Create a new file with name
B.php
- Past and save
B.php
).

So if i want to extract lines from 3 to 8 (for example) in the following code

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<?php
$fname= basename(__FILE__,'php');
?>
<title><?php echo $fname; ?></title>
</head>
<body>
<p>This is a test Page</p>
</body>
</html>


How can i do this in details if you can?

Answer

From the documentation here:

http://php.net/manual/en/function.file.php

This command splits the file into an array of lines:

// substitute a local file for the URL
$lines = file('http://php.net/manual/en/function.file.php');
echo $lines[0];
// <!DOCTYPE html>
echo $lines[56];
//  <![endif]-->

After you have the lines you want you can create a new file and save it. There are 100 ways to do this. Here is one:

http://php.net/manual/en/function.file-put-contents.php

file_put_contents('fileInCurrentDirectory.php', $lines[3], FILE_APPEND | LOCK_EX);

file_put_contents('fileInCurrentDirectory.php', $lines[4], FILE_APPEND | LOCK_EX);

file_put_contents('fileInCurrentDirectory.php', $lines[5], FILE_APPEND | LOCK_EX);
Comments