note 126620 added to class.domdocument

From: Date: Wed, 17 Nov 2021 13:16:42 +0000
Subject: note 126620 added to class.domdocument
Groups: php.notes 
Request: Send a blank email to php-notes+get-217260@lists.php.net to get a copy of this message
After struggling with parsing and modifying partial HTML content for several hours, I came to this solution which does work for me and is relatively simple compared to what else I found online. This solution fixes unwanted DOCTYPE and html, body tags as well as encoding issues. <?php // Assumption: content is utf-8 encoded $content = "<h1>This is a heading</h1><p>This is a paragraph</p>"; // Load content to a div and specify encoding with a meta tag $temp_dom = new DOMDocument(); $temp_dom->loadHTML("<meta http-equiv='Content-Type' content='charset=utf-8' /><div>$content</div>"); // As loadHTML() adds a DOCTYPE as well as <html> and <body> tag, let’s create another DOMDocument and import just the nodes we want $dom = new DOMDocument(); $first_div = $temp_dom->getElementsByTagName('div')[0]; $first_div_node = $dom->importNode($first_div, true); $dom->appendChild($first_div_node); // Do whatever you want to do $dom->getElementsByTagName('h1')[0]->setAttribute('class', 'happy'); // You could also just echo $dom->saveHtml() if you don’t mind the div and whitespace echo substr(trim($dom->saveHtml()), 5, -6); // Outputs: <h1 class="happy">This is a heading</h1><p>This is a paragraph</p> ?> ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.85.242 (proxied: 176.66.227.253) ---- Manual Page -- https://php.net/manual/en/class.domdocument.php Edit -- https://main.php.net/note/edit/126620 Del: integrated -- https://main.php.net/note/delete/126620/integrated Del: useless -- https://main.php.net/note/delete/126620/useless Del: bad code -- https://main.php.net/note/delete/126620/bad+code Del: spam -- https://main.php.net/note/delete/126620/spam Del: non-english -- https://main.php.net/note/delete/126620/non-english Del: in docs -- https://main.php.net/note/delete/126620/in+docs Del: other reasons-- https://main.php.net/note/delete/126620 Reject -- https://main.php.net/note/reject/126620 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#217260) next »