SimpleXML - Get Node/Attribute Values
SimpleXML is a PHP extension that allows us to easily manipulate and get XML data.
PHP SimpleXML - Get Node Values
Get the node values from the "note.xml" file:
Example
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
echo $xml->to . "
";
echo $xml->from . "
";
echo $xml->heading . "
";
echo $xml->body;
?>
The output of the code above will be:
Tove
Jani
Reminder
Don't forget me this weekend!
Another XML File
Assume we have an XML file called "books.xml", that looks like this:
Everyday Italian
Giada De Laurentiis
2005
30.00
Harry Potter
J K. Rowling
2005
29.99
XQuery Kick Start
James McGovern
2003
49.99
Learning XML
Erik T. Ray
2003
39.95
PHP SimpleXML - Get Node Values of Specific Elements
The following example gets the node value of the
element in the first and second elements in the "books.xml" file:
Example
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
echo $xml->book[0]->title . "
";
echo $xml->book[1]->title;
?>
The output of the code above will be:
Everyday Italian
Harry Potter
PHP SimpleXML - Get Node Values - Loop
The following example loops through all the elements in the "books.xml" file, and gets the node values of the, , , and elements:
Example
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) {
echo $books->title . ", ";
echo $books->author . ", ";
echo $books->year . ", ";
echo $books->price . "
";
}
?>
The output of the code above will be:
Everyday Italian, Giada De Laurentiis, 2005, 30.00
Harry Potter, J K. Rowling, 2005, 29.99
XQuery Kick Start, James McGovern, 2003, 49.99
Learning XML, Erik T. Ray, 2003, 39.95
PHP SimpleXML - Get Attribute Values
The following example gets the attribute value of the "category" attribute of the first element and the attribute value of the "lang" attribute of theelement in the second element:
Example
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
echo $xml->book[0]['category'] . "
";
echo $xml->book[1]->title['lang'];
?>
The output of the code above will be:
COOKING
en
PHP SimpleXML - Get Attribute Values - Loop
The following example gets the attribute values of the
elements in the "books.xml" file:
Example
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) {
echo $books->title['lang'];
echo "
";
}
?>
The output of the code above will be:
en
en
en-us
en-us