How To Edit A File Using PHP
Updated Tuesday, May 14, 2024, 6 PM
You can edit most files using php, it's relatively easy.
You need a target file and target keyword that needs editing , for you to easily understand, we are going to edit an html file.
We will target the title of this html, if you don't already know, the title is the most important line in a web page because it provides the Web page its name. without title, you would just see the current page link in browser name fields.
So we are going to edit the content inside the title, we will replace the content inside the title with another content that we hardcoded in the following php script
We hardcoded the title content in this script as an example. for an advanced usage, you will need add an input filed and enter your favourite text for the title.
Target file to edit using PHP
First, you will need an html file, like index.html file and you beed provide a path to the html file
After the target file is created, you will need to provide the path to the html file in the script and the add the new title content, that's it.
After the above changes, you just need load the php file by entering its URL in the browser, it will then be executed and the script will run and do the changes that you put
Which type of files can be edited with PHP?
Most text files can be edited with the PHP. You can even edit a PHP file itself using a php script
PHP script to edit files
<?php // File path of the HTML file
$htmlFilePath = 'path/to/your/file.html';
// Read the content of the HTML file
$htmlContent = file_get_contents($htmlFilePath);
// Modify the title in the HTML content
$newTitle = 'New Title'; $htmlContent = preg_replace('/<title>(.*?)<\/title>/', '<title>' . $newTitle . '</title>', $htmlContent);
// Write the updated content back to the file
file_put_contents($htmlFilePath, $htmlContent);
echo "Title updated successfully!"; ?>
Copy the above code to a php file, for example, myscript.php and then you can run the script and see the changes in target file.
Let us know know in the comments if you have any questions
No comments yet