Get element value in two level down in PHP
Description
The following code shows how to get element value in two level down.
Example
/* w ww . j a v a2 s . c o m*/
<?php
$xml = simplexml_load_file('test.xml');
?>
<!DOCTYPE html>
<html>
<body>
<?php
foreach ($xml->book as $book) {
echo '<h2>' . $book->title . '</h2>';
$num_authors = count($book->author);
echo '<p class="author">';
for ($i = 0; $i < $num_authors; $i++) {
echo $book->author[$i];
// If there's only one author, break out of the loop
if ($num_authors == 1) {
break;
} elseif ($i < ($num_authors - 2)) {
// If there are more than one authors left, use a comma
echo ', ';
} elseif ($i == ($num_authors - 2)) {
// Otherwise insert an ampersand
echo ' & ';
}
}
echo '</p>';
echo '<p class="publisher">' . $book->publisher . '</p>';
echo '<p class="publisher">ISBN: ' . $book['isbn13'] . '</p>';
echo '<p>' . $book->description . ' Price: '. $book->price->paperback . ' (paperback), ' . $book->price->ebook . ' (ebook).</p>';
}
?>
</body>
</html>
The following code is for test.xml.
<?xml version='1.0' encoding='utf-8'?>
<inventory>/*ww w.ja v a 2s. c om*/
<book isbn13='1'>
<title>PHP</title>
<author>Jack</author>
<publisher>Pub 1</publisher>
<description>PHP Book</description>
<price>
<paperback>$3.99</paperback>
<ebook>$2.89</ebook>
</price>
</book>
<book isbn13='2'>
<title>XML</title>
<author>Jane</author>
<publisher>Pub 2</publisher>
<description>XML Book</description>
<price>
<paperback>$4.99</paperback>
<ebook>$3.99</ebook>
</price>
</book>
</inventory>