I'm using this code to extract all required nodes from xml:
$xml = simplexml_load_file('file.xml');
echo "<strong>Using direct method...</strong><br />";
$items = $xml->xpath('/w:document/w:body/w:tbl/w:tr/w:tc/w:p/w:r/w:t');
foreach($items as $item) {
echo "Found $item<br />";
}
I'm getting a long list of entries, but I need possibility to choose any of them seperately. tried to use echo "Found $item[2]<br />";
but got error:
Warning: main() [function.main]: Cannot add element t number 1 when only 0 such elements exist
thanks for advices
If you want to extract the 2nd w:t
element use the index in xpath instead.
$item = list($xml->xpath('(/w:document/w:body/w:tbl/w:tr/w:tc/w:p/w:r/w:t)[3]'));
Note 3
means 3rd w:t
element. Xpath Index starts from 1
instead of 0
. And list
is used to fetch the first element as Xpath always returns an array.
Also note this XPath can be reduced to (//w:r/w:t)[3]
unless same tree is available somewhere else. So it looks like
$item = list($xml->xpath('(//w:r/w:t)[3]'));
it should be echo "found $items[2]<br />";
instead of $item[2]