How can XML attributes be accessed directly in PHP?

To access XML attributes directly in PHP, you can use the SimpleXMLElement class along with the attributes() method to retrieve the attribute values. This method allows you to access the attributes of an XML element by their name. You can then use the attributes as needed in your PHP code.

$xml = '<book genre="fiction"><title>The Great Gatsby</title></book>';
$book = new SimpleXMLElement($xml);

// Accessing the genre attribute
$genre = $book->attributes()['genre'];

echo $genre; // Output: fiction