Reading XML Help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rpflo
Forum Newbie
Posts: 1
Joined: Sun Feb 10, 2008 9:40 pm

Reading XML Help

Post by rpflo »

Hello! First post for me here. I'm very new to PHP and programming in general (1 month, actually, for both), but I'm learning faster than I expected.

I've figured out how to read and add elements to an xml file--but only what the tutorials have shown me i.e.:

Code: Select all

 
$xml = new SimpleXMLElement('new.xml', null, true);
foreach ($xml->movie[0]->characters->character as $c) {
    echo $c->name, ' - played by: ';
    echo $c->actor, '<br />';
}
That's nice, but I have to know the position of the movie element [0] to list all of it's element values.
I am going to be making regularly updating an xml file with every main element having an attribute that is a date stamp.

i.e.

Code: Select all

 
<entries>
  <entry date="2008_02_02_15_56">
    <blah>Blah blah</blah>
    <blah2>Blah blah</blah2>
  </entry>
  <entry date="2008_02_07_12_23">
    <blah>Blah blah</blah>
    <blah2>Blah blah</blah2>
  </entry>
</entries>
 
Obviously the first entry is [0] and the second [1], so to display their contents I could simply point to [0] or [1]. But I'd rather it figured it out on its own. If I know the date stamp I'm looking for and plop it into a variable, how can I get it to figure out which number [0] or [1] on the tree that is, and therefore use the variable to find the parent element in the xml file to display it's contents?

Thanks so much in advance. If I wasn't clear please ask for clarification.

If I'm too new for this forum, please put my email address on some spam list and torch this post. :oops:
User avatar
novice4eva
Forum Contributor
Posts: 327
Joined: Thu Mar 29, 2007 3:48 am
Location: Nepal

Re: Reading XML Help

Post by novice4eva »

Hi there, since you can loop through the XML file, i think putting a counter will do the trick. I have not worked much with XML, but taking the exact example that you gave, it would look something like this:

Code: Select all

 
    $all_message = $dom->getElementsByTagName("entry");
    foreach($all_message as $key=>$message) 
    {
        if($message->getAttribute('date')==$date_you_were_checking_for)
                {
                     echo $key. ' is the number you were looking for';
                     break;
                }
        }
 
Hope it helped :mrgreen:
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Re: Reading XML Help

Post by timvw »

I would probably use XPath to find the node...

//entry[@date='2008_02_02_15_56']
Post Reply