• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Access an element’s attributes with PHP’s SimpleXML extension

Access an element’s attributes with PHP’s SimpleXML extension

The PHP SimpleXML extension makes it easy to work with XML files by creating an object from the XML structure. To access an element’s attributes, use the property() method for that element.

XML Example

The following examples use this as the XML string:

<data>
    <items>
        <item>
            <sometag myattribute="foo">first node</sometag>
        </item>
        <item>
            <sometag myattribute="bar">second node</sometag>
        </item>
    </items>
</data>

Get the "myattribute" attributes

First create the SimpleXML attribute. The above XML has already been loaded into a variable called $xml:

$xmlobj = new SimpleXMLElement($xml);

To access the value for the first <sometag> node from the first <item> do this:

echo $xmlobj->items->item[0]->sometag;

To access the "myattribute" attribute from the <sometag> node from the first <item> do this:

echo $xmlobj->items->item[0]->sometag->attributes()->myattribute;

To loop through all the <item> nodes and echo out the "myattribute" attribute and value for each of the <sometag> nodes do something along the lines of this:

foreach($xmlobj->items->item as $item) {
    echo "Attribute: " . $item->sometag->attributes()->myattribute . "n
    echo "Value: " . $item->sometag . "nn";
}

This will output:

Attribute: foo
Value: first node

Attribute: bar
Value: second node

Check Out These Related posts:

  1. Get the Feedburner original link with PHP
  2. Google Analytics API dimensions vs metrics
  3. Extracting attachments from an email message using PHP IMAP functions
  4. Set multiple attributes at once with jQuery

Filed Under: PHP

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap