ivopetkov / html5-dom-document-php

A better HTML5 parser for PHP.
MIT License
599 stars 40 forks source link

How do I get the attributes of any element? #35

Closed imsaeedafzal closed 4 years ago

imsaeedafzal commented 4 years ago

Hi. I found your library very useful and good written. Appreciated!

Can you please help me how do I get the attributes of any element? And how do I replace the attribute value, element innerHtml, and outerHtml?

Thanks in advance.

ivopetkov commented 4 years ago

Hi, here is an example code that will answer your question:

$html = '<html><body><div class="red"></div></body></html>';
$dom = new \IvoPetkov\HTML5DOMDocument();
$dom->loadHTML($html);

print_r($dom->querySelector('div')->getAttributes());
// Output:
// Array
// (
//     [class] => red
// )

$dom->querySelector('div')->setAttribute('name', 'value');
echo $dom->querySelector('div')->outerHTML;
// Output:
// <div class="red" name="value"></div>

$dom->querySelector('div')->outerHTML = '<div>hi</div>';
echo $dom->saveHTML();
// Output:
// <!DOCTYPE html>
// <html><body><div>hi</div></body></html>

$dom->querySelector('div')->innerHTML = '<span>hello</span>';
echo $dom->saveHTML();
// Output:
// <!DOCTYPE html>
// <html><body><div><span>hello</span></div></body></html>
imsaeedafzal commented 4 years ago

Great, thank you.