If I have a block of HTML and want to get the exact HTML content for certain nodes and child nodes, for example the <ul>
block below, should I use something like preg_match
or parse the content or something like DOM Parsing?
Input
<html>
<head>
</head>
<body>
<h2>List</h2>
<ul class="my-list" id="my-list">
<li class="item first">item1</li>
<li class="item second">item2</li>
<li class="item third">item3</li>
</ul>
</body>
</html>
Desired output
<ul class="my-list" id="my-list">
<li class="item first">item1</li>
<li class="item second">item2</li>
<li class="item third">item3</li>
</ul>
As you can see I want to preserve all the attributes (classes, ids, etc).
I know that with DOM
parsing I can access all of those attributes ($items->item($i)->getAttribute('class')
), but can DOM handle easily (and automatically) rebuilding just a section of the original code without having to manually loop through and build the HTML? (I know DOM
has echo $DOM->saveXML()
, but iI believe that is just for the entire page.
I know how I can accomplish this with regex and PHP fairly easily, but I'm thinking that is not a good practice.
This is so simple with jQuery:
jQuery('ul').clone()
How can I achieve the same thing with PHP? (grabbing remote HTML, and getting a slice of it using DOM and outputting it as HTML again)