I wonder how I can manipulate the DOM tree using PHP?
I have seen some answers with XML DOM that loads in a html file. But what if I don't need to load? What if have XML DOM scripts inside the document I want to manipulate?
I have an example below that prints out all the folders. Fill in the blanks in your answers. I want to create div-elements with the folder's name as text node. The answer need to have some XML DOM scripts because I will create more elements than just one div-element in my website. And using for example echo is not practical, because you might insert an element inside the wrong element etc.
$sql = "
SELECT name
FROM folders
WHERE profileId = '$profileId'
";
$result = mysql_query($sql) or die('Error6: '.mysql_error());
while($row = mysql_fetch_array($result)) {
}
You don't need PHP to manipulate the dom of a document you're generating already. It's by far easier to just have PHP directly generate some HTML. DOM's there to disect/change HTML that was generated elsewhere. In other words, your script would just be:
while($row = mysql_fetch_array($result)) {
echo "<div>{$row['name']}</div>";
}
DOM example, to demonstrate the tediousness
Ok, here's the PHP method to generate a paragraph of text with some internal spans and whatnot:
echo "<div> This is my div, <span>There are many like it, <b>but this one</b> is</span> mine</div>";
The equivalent DOM calls: (not tested, just to demonstrate):
$dom = new DOM;
$bold = new DOMElement('b');
$bold->appendChild(new DOMText('but this one'));
$span = new DOMElement('span');
$span->appendChild(new DOMText('There are many like it,'));
$span->appendChild($bold);
$span->appendChild(new DOMText(' is');
$div = new DOMElement('div');
$div->appendChild(new DOMText(' This is my div,'));
$div->appendChild($span);
$div->appendChild(' mine');
echo $div->saveXML();
So....... still thing using DOM is easier than using echo?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With