PHP Tutorial - PHP attributes() Function

The attributes() function returns attributes and values within an XML tag.


PHP attributes() Function has the following syntax.



ParameterIs RequiredDescription
nsOptional.A namespace for the retrieved attributes
is_prefixOptional.A Boolean value. TRUE if ns is a prefix. FALSE if ns is a URI. Default is FALSE


Returns a SimpleXMLElement object on success.


Return attributes and values within the XML body element:

<?php/*w w  w  . j a va  2  s. c  o m*/
    <name date="2013-01-01" type="public">PHP</name>
    <name date="2013-01-01" type="private">Java</name>

foreach($xml->body[0]->attributes() as $a => $b){
   echo $a,'="',$b,"\"\n";

Example 2

The following code shows how to access attribute and element value.

<?php/* w ww.j a va2s .co m*/
$xml = simplexml_load_file('test.xml');
<!DOCTYPE html>
foreach ($xml->book as $book) {
  echo '<h2>' . $book->title . '</h2>';
  $num_authors = count($book->author);
  echo '<p class="author">';
  foreach ($book->author as $author) {
    echo $author;
  for ($i = 0; $i < $num_authors; $i++) {
    echo $book->author[$i];
    if ($num_authors == 1) {
    } elseif ($i < ($num_authors - 2)) {
      echo ', ';
    } elseif ($i == ($num_authors - 2)) {
      echo ' &amp; ';
  echo '</p>';
  echo '<p class="publisher">' . $book->publisher . '</p>';
  echo '<p class="publisher">ISBN: ' . $book['isbn13'] . '</p>';
  echo '<p>' . $book->description . '</p>';

The following code is for test.xml.

<?xml version='1.0' encoding='utf-8'?>
  <book isbn13='1'>
  <publisher>Publisher 1</publisher>
  <description>PHP Book</description>
  <book isbn13='2'>
  <publisher>Publisher 2</publisher>
  <description>XML Book</description>

The code above generates the following result.