Access/Use SimpleXMLElement::attributes

By: padya

25 Jul 2011

It is really simple to access attributes using array form. However, you must convert them to strings or ints if you plan on passing the values to functions.

[$xml] = SimpleXMLElement Object
  
(
      [@
attributes] => Array
          (
              [
id] => 55555
         
    [text] => "hello world"
          )
  
)

Then using a function

<?php
function xml_attribute($object, $attribute)
{
    if(isset(
$object[$attribute]))
        return (string)
$object[$attribute];
}
?>

I can get the "id" like this
 

<?php
print xml_attribute($xml, 'id'); //prints "55555"

?>

 

OR

You can simply breakdown into more simpler and easier by simply writing

<?php

print (string) $xml['id'];

?>

 

 

No Responses yet to Access/Use SimpleXMLElement::attributes

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

1 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.

php.png    firefox.png    open_source.png    ubuntu.png    drupal.png    civicrm.png     jquery

About the Author

Recent comments

Follow Me

flickr.png    yahoo.png    facebook.png    twitter.png

google.png    youtube.png    wordpress.png   

       wordpress.png

Ohloh profile for rahulbile

User login