How can I access and modify attributes of elements in a DOM object in PHP?

To access and modify attributes of elements in a DOM object in PHP, you can use the DOMDocument and DOMXPath classes. First, load the HTML content into a DOMDocument object, then use DOMXPath to query for the specific element you want to modify. Once you have the element, you can access and modify its attributes using the setAttribute() and getAttribute() methods.

// Load the HTML content into a DOMDocument object
$dom = new DOMDocument();
$dom->loadHTML($html);

// Use DOMXPath to query for the specific element you want to modify
$xpath = new DOMXPath($dom);
$element = $xpath->query('//div[@id="example"]')->item(0);

// Access and modify attributes of the element
$element->setAttribute('class', 'new-class');
$element->setAttribute('data-custom', '123');

// Get the value of an attribute
$customData = $element->getAttribute('data-custom');

// Save the modified HTML content
$modifiedHtml = $dom->saveHTML();