How can attributes be accessed and extracted from XML elements in PHP?

To access and extract attributes from XML elements in PHP, you can use the SimpleXMLElement class which represents an XML element. You can access attributes by treating the element as an object and using the arrow notation followed by the attribute name. You can then extract the attribute value by simply accessing the attribute as a string.

$xml = '<bookstore><book genre="fiction">Harry Potter</book></bookstore>';
$element = new SimpleXMLElement($xml);
$genre = $element->book['genre'];
echo $genre; // Output: fiction