Jump to content

Simplexml, accessign data


nikohak

Recommended Posts

Hi,

What do I need to write to get the content of xml page-tag that has id "story2" to appear on the screen, in other words: "head2"?

I have the xml already loaded with simplexml into $myXml variable and it works just fine, but this particular thing is giving me headache.

 

So it's something like: echo $myXml->page...

 

Here is the XML:

 

<?xml version="1.0" encoding="utf-8"?>

<content>

<page id="story1" langurl="1">head1</page>

<page id="story2" langurl="2">head2</page>

<page id="story3" langurl="3">head3</page>

<page id="story4" langurl="4">head4</page>

<page id="story5" langurl="5">head5</page>

<page id="story6" langurl="6">head6</page>

</content>

Link to comment
https://forums.phpfreaks.com/topic/185474-simplexml-accessign-data/
Share on other sites

this should help, not too sure if this is the most optimal way to do it though

 

<?php

$str = '<?xml version="1.0" encoding="utf-8"?>
<content>
<page id="story1" langurl="1">head1</page>
<page id="story2" langurl="2">head2</page>
<page id="story3" langurl="3">head3</page>
<page id="story4" langurl="4">head4</page>
<page id="story5" langurl="5">head5</page>
<page id="story6" langurl="6">head6</page>
</content>
';

$xml = simplexml_load_string($str);

for ($i=0;$i<count($xml->page);$i++) {
    $attribs = getAttributes($xml->page[$i]);

    if ($attribs['id'] == 'story2') {
        echo $xml->page[$i];
    }
}

function getAttributes(&$node) {
    $attribs = array();
    foreach ($node->attributes() as $name => $attr) {
        $attribs[$name] = (string) $attr[0];
    }
    return $attribs;
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.