Google News
logo
Get node values of specific elements in PHP
To get the node values of specific elements in PHP, you can use the SimpleXML extension. Here's an example code that demonstrates how to do this :
Program :
$xmlString = <<<XML
<books>
    <book>
        <title>1984</title>
        <author>George Orwell</author>
        <publisher>Penguin Books</publisher>
    </book>
    <book>
        <title>The Catcher in the Rye</title>
        <author>J. D. Salinger</author>
        <publisher>Little, Brown and Company</publisher>
    </book>
</books>
XML;

$xml = simplexml_load_string($xmlString);

foreach ($xml->book as $book) {
    echo "Title: " . $book->title . "<br>";
    echo "Author: " . $book->author . "<br>";
    echo "Publisher: " . $book->publisher . "<br><br>";
}
This code creates an XML string, loads it into a SimpleXMLElement object using `simplexml_load_string()`, and then loops through each `<book>` element in the XML, outputting the title, author, and publisher of each book.

Note that you can access the value of an element using the element name as a property of the SimpleXMLElement object.