How to get simplexml attributes in php?

Member

by daisha , in category: PHP General , a year ago

How to get simplexml attributes in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , a year ago

@daisha 

To get attributes from a SimpleXMLElement object in PHP, you can use the attributes() method. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
$xmlString = '<?xml version="1.0" encoding="UTF-8"?>
<book category="Fiction">
    <title>The Great Gatsby</title>
    <author>F. Scott Fitzgerald</author>
</book>';

$xml = simplexml_load_string($xmlString);

$category = $xml->attributes()->category;
$title = (string) $xml->title;
$author = (string) $xml->author;

echo "Category: " . $category . "
";
echo "Title: " . $title . "
";
echo "Author: " . $author . "
";


Output:

1
2
3
Category: Fiction
Title: The Great Gatsby
Author: F. Scott Fitzgerald


In this example, the attributes() method is used to retrieve the value of the "category" attribute. The (string) cast is used to convert the SimpleXMLElement object to a string for the title and author elements.