Suppose I have this in a file called data.xml:
<?xml version="1.0"?>
<stats>
<data1>lorem</data1>
<data2>ipsum</data2>
<source mount="/mno">
<thing>1.0</thing>
<somethingelse>10</somethingelse>
<important>12345</important>
<more>word</more>
</source>
<source mount="/pqr">
<thing>1.0</thing>
<somethingelse>10</somethingelse>
<important>23456</important>
<more>word</more>
</source>
<source mount="/stu">
<thing>1.0</thing>
<somethingelse>10</somethingelse>
<important>34567</important>
<more>word</more>
</source>
<source mount="/vwx">
<thing>1.0</thing>
<somethingelse>10</somethingelse>
<important>45678</important>
<more>word</more>
</source>
</stats>
I now need to extract the contents of specifically the element <important> that's under <source mount="/stu">, and display this on a web page.
I figured out I can do that like this:
<?php
$xml=simplexml_load_file("data.xml") or die("Error: Cannot create object");
echo $xml->source[3]->important;
?>
This actually works. What I do here is go to the third <source> which happens to be the one I need. However... The contents of the XML may (and will) change, and when that happens, <source mount="/stu"> may not be the third one anymore, which means the output would no longer be that of the specific element I need here.
How do I make it so that it will always display the contents of <important> from specifically <source mount="/stu">, even if the number of items in the XML changes?
I've been told XPATH could be the way to go, but coding is not my profession, and I find it hard to get my head around... I've also studied some other XML related questions here on StackOverflow, but my novice brain does not understand how to apply those to my situation. So any advise would be welcome here. Is XPATH indeed a good idea? If so, how do I implement/use that here. Or are there other/better ways of doing this?
Many thanks.