Use the DOMDocument
class to represent your document as an object. Query for the ID you're seeking, and add a class onto it. From there you can spit the HTML back out.
Simple example:
// HTML to be handled (could very well be read in)
$html = "<!DOCTYPE html><html><body><p id='foo'>Foo</p></body></html>";
// Create and load our DOMDocument object
$doc = new DOMDocument();
$doc->loadHTML($html);
// Find and manipulate our paragraph
$foo = $doc->getElementById("foo");
$foo->setAttribute("class", "bar");
// Return the entire document HTML
echo $doc->saveHTML();
Alternatively, if you only wanted the HTML for the affected element:
echo $doc->saveHTML($foo);
The generated HTML follows:
<!DOCTYPE html>
<html>
<body>
<p id="foo" class="bar">Foo</p>
</body>
</html>
Note that the above code doesn't first check to see if the class attribute is already present on the element. You should perform that check so as to not lose any pre-existing classes that might already be on the element.