Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit an HTML file using PHP

Tags:

html

php

I have a simple form where you can upload an html file, its structure looks like this:

<?xml version='1.0' encoding='utf-8'?>
<html xmlns="http://www.w3.org/1999/xhtml" lang="he" xml:lang="he" dir="rtl">

<head>
  <title>test</title>
  <link rel="stylesheet" href="../Styles/cssreset-min.css" type="text/css"/>
  <link rel="stylesheet" href="../Styles/page_styles.css" type="text/css"/>
  <link rel="stylesheet" href="../Styles/style.css" type="text/css"/>   
</head>

<body id="start">

  <img src="../Images/cover.jpg" class="images" alt="Image 1"/>

</body>

</html>

I'm interested in the server-side coding of editing the HTML file, how do I load it, find the img tag and replace it with <svg> tag (for example) and save the html file with the same name and extension. I've tried a number of times but I seems to get confused with with all the different methods out there. This solution needs to be cross-browser compatible and don't use any dependency if possible, e.g. I tried using RecursiveTreeIterator once and my hosting company was blocking it from running.

Thanks

like image 456
odedta Avatar asked Sep 13 '25 22:09

odedta


1 Answers

Are you looking for something like this ?

$html=file_get_contents($html_file);
$img_tag= strip_tags($html, '<img><img/>');
$svg_tag='<svg>...';
$html=str_replace($img_tag,$svg_tag,$html);
file_put_contents($html_file,$html);

See strip_tags

like image 72
Uri Goren Avatar answered Sep 15 '25 10:09

Uri Goren