Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting node Value of last Child

Tags:

php

xml

xmlnode

This question may seem very stupid, but I am not able to find much help on how to find the node value of the last child using PHP, even though it's a piece of cake with JS. This is what my XML currently looks like:

<?xml version="1.0"?>
<files>
 <file>.DS_Store</file>
 <file>ID2PDF_log_1.xml</file>
 <file>ID2PDF_log_12.xml</file>
 <file>ID2PDF_log_15.xml</file>
</files>

Here's the php code:

$filename = 'files.xml'; //my xml file name
$dom = new DomDocument();
$dom->load($filename);

$elements = $dom->getElementsByTagName('file');
echo $elements->lastChild(); // This is obviously not working
/*I get an error that I am trying to access an undefined method in DOMNodeList. Now, I know
that lastChild is a property of DOMNode. But I can't figure out how I can change my code to 
get this to work.*/  

I am trying to echo out

ID2PDF_log_15.xml

Can anyone show me how to get this done?

P.S.: I don't want to change the xml file structure because I am creating it through a script and I am a lazy programmer. But, I did do my research to get this. Didn't help.

I did try getting the number of elements in the node 'file' and then using item(#), but that didn't seem to work either.

Thanks

SOLUTION

$filename = 'files.xml';
$dom = new DomDocument();

$dom->load($filename);

$elements = $dom->getElementsByTagName('file')->length;
echo 'Total elements in the xml file:'.$elements."\n";

$file = file_get_contents('files.xml');
$xml = simplexml_load_string($file); 

$result = $xml->xpath('file');
echo "Last element".$result[$elements-1]."\n";

I'll make this neater a little later. But, just thought that I should share the answer anyway any new users in the future.

like image 457
Watchful Protector Avatar asked Dec 21 '22 11:12

Watchful Protector


1 Answers

This should work:

$elements->xpath('root/child[last()]');

Read up about xpath

Alternatively I would suggest counting the number of elements, and then targeting the last element using that count:

$file_count = $elements->getElementsByTagName('file')->length;
$elements[$file_count];
like image 77
jacktheripper Avatar answered Dec 23 '22 02:12

jacktheripper