tags:

views:

29

answers:

2

I have a xml file

<?xml version="1.0" encoding="UTF-8"?>
<xml>
<settings>
<title>Calendar for September</title>
<subTitle>Calendar for September  Calendar for September</subTitle>
</settings>
<events date="06-09-2010">
<event id="2">
<title>This is My Second Event</title>
<description>This is My Second Event </description>
</event>
<event id="3"><title>This is My Third  Event </title><description>This is My Third  Event This is My Third  Event This is My Third  Event </description></event></events>
</xml>

I am parsing the xml file using

$xml_str = file_get_contents('xmlfile');
$xml = simplexml_load_string($xml_str);
if(!empty($xml))
{
 $nodes = $xml->xpath('//xml/events/event[@id="'.$id.'"]');
}

It will give only the title and description of event tag with specified id.How i can get the date

+1  A: 

Try

//event[@id="2"]/parent::events/@date

Together with the original XPath:

//event[@id="2"]/parent::events/@date | //event[@id="2"]
KennyTM
Thanks KennyTM.But it will give only date.
THOmas
@THOmas: You could `|` with the original XPath.
KennyTM
sorry i didnt get u.Can u edit ur answer
THOmas
@THOmas: `//event[@id="2"]/parent::events/@date | //event[@id="2"]`
KennyTM
Thanks KennyTM it is working fine .Can u update the answer
THOmas
@KennyTM: Two minor: whenever schema is well know, try to avoid starting `//` operator, the abbreviated syntax `..` is also well know. So this could be: `/*/*/event[@id='2']|/*/*/event[@id='2']/../@date`. Also, with "context free" expresion is a good practice to select in one direction only like `/*/events[event[@id='2']]/@date`.
Alejandro
A: 

Once you've found the <event> element use it as the context node for a new xpath query that fetches the nearest <events> element in the ancestor-axis.

$id = 2;
$xml = simplexml_load_file('xmlfile');
if( !$xml ) {
  echo '!xml doc';
}
else if ( !($event=$xml->xpath('events/event[@id="'.$id.'"]')) ) {
  echo '!event[id=...';
}
else if ( !($container = $event[0]->xpath('ancestor::events[1]')) ) {
  echo '!events parent';
}
else {
  echo $container[0]['date'], ' - ', $event[0]->title, "\n";
}
VolkerK