Page 1 of 1

XML and Php

Posted: Wed May 09, 2007 4:21 am
by user___
Hi guys,
I asked this a short time ago but I got no answer. I hope that now there would be someone who could help.

Well, I have a .xml file which has a root tag and subtags. In each subtag there is an id. I need to get the last id of a subtag in the list.
This is a sample of my .xml

Code: Select all

...
<root>
   <list id="1" />
   <list id="2" />
   <list id="3" />
</root>
...
I need to get three as a value from my Php script.

I would like to know whether this is possible with Php(and how if it is) or not.

Posted: Wed May 09, 2007 4:28 am
by Oren
What's your PHP version?

Posted: Wed May 09, 2007 4:53 am
by CoderGoblin
A lot depends on how large and complex your XML is possibly going to be. Options if small include things like preg_match_all. If larger/more complex than your example you may wish to look at actually processing your XML using something like SimpleXML or one of the other PHP XML libraries such as XML Parser Functions. The main trouble with XML parsing is to ensure that the original data is well formed, even if it not valid (matched to a specific Document Type Definition (DTD)).

Hope that helps

Coder

Reply

Posted: Wed May 09, 2007 5:20 am
by user___
Oren: I use Php 5.
CoderGoblin:Thank you for the reply. My XML is simple in structure the same as I posted and there can be one more child in it. The content may become a lot(list tags can be hundreds).

Posted: Wed May 09, 2007 5:40 am
by CoderGoblin
The next question you need to ask then is how am I getting this information in. Is it line by line or is a string. If you are reading line by line then it should be easy to use simply keep a running tag on every occurance of the list. If it is a string already I would use preg_match (personal preference). If the lists are always running from 1-x seqentially all you would need to do is count the occurances of the <list> tags. If not you need to work out a pattern to extract the last list attribute.

Reply

Posted: Wed May 09, 2007 7:49 am
by user___
Thank you, CoderGoblin for your reply. Actually, I need to get the number of ids but although you explained me how to do it very well, I would appreciate it if you could post me a sample code on how to do it.

BTW:Lines are running sequentially.

Posted: Wed May 09, 2007 7:57 am
by volka
user___ wrote:BTW:Lines are running sequentially.
Then you can use the xpath 1.0 function last()

Code: Select all

$xml = <<< eox
<root>
   <list id="1" />
   <list id="2" />
   <list id="3" />
</root>
eox;


$dom = new DOMDocument::loadXML($xml);

$xpath = new DOMXPath($dom);
$nodeset = $xpath->query('//list[last()]/@id');
echo $nodeset->item(0)->nodeValue;