R
R
Ruslan Leviev2012-04-14 15:10:54
PHP
Ruslan Leviev, 2012-04-14 15:10:54

SimpleXML, namespaces and tag attributes?

I'm trying to parse data about a LJ user. Read resource exampleusername.livejournal.com/data/foaf , load it into SimpleXML:

$input_xml = simplexml_load_string(file_get_contents('http://exampleusername.livejournal.com/data/foaf'));

Since the XML there is unusual, and with many namespaces, in order to extract useful data, you have to load the descriptions of these namespaces. So, for example, we get the name and date of birth of the user:
$person = $input_xml->children('http://xmlns.com/foaf/0.1/');
echo $person->Person->name.'<br/>';
echo $person->Person->dateOfBirth;

Now I'm trying to extract the blog creation date, doing the following:
$blog = $person->Person->weblog->children('http://www.livejournal.org/rss/lj/1.0/');

Now if we make var_dump() the $blog variable, we will see the following:
object(SimpleXMLElement)#4 (1) {
  ["@attributes"]=>
  array(2) {
    ["dateCreated"]=>
    string(19) "2008-12-15T18:00:10"
    ["dateLastUpdated"]=>
    string(19) "2012-03-16T09:49:22"
  }
}

However, calling $blog->attributes() results in the error "Warning: var_dump(): Node no longer exists in /var/www/test.php on line 45" , and the $blog['dateCreated'] associative array doesn't work either. What am I doing wrong?
Parsed XML File Example

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dali, 2012-04-14
@ruskar

get this tag in $tag then try like this:

$attr = $tag->attributes("lj", 1);
$dc = $attr["dateCreated"];

R
rPman, 2012-04-14
@rPman

The problem is that there is a '@' symbol in the attribute name, the solution is to convert the object into an associative array and refer to the attribute as an array element:

$bug_blog=(array)$blog;
var_dump($bug_blog['@attributes']);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question