Reputation: 987
I don't usually have to do any backend stuff, but for this one project I have to parse XML using PHP so it's all kind of new and very complicated to me. I need to display the fourth tag on a page and I figured I would use getElementsByTagName but the trouble is the three previous tags are the same, so it looks something like this:
<Person fname="John" lname="Smith"/>
<Person fname="Frank" lname="Jones"/>
<Person fname="Mike" lname="Jackson"/>
<Person fname="Jack" lname="Williams"/>
<value no="50"/>
<value no="60"/>
<value no="70"/>
Here is what I would like to output in my HTML page using the first attribute in the fourth tag and the attribute in the second tag:
Mike: 60
Basically, is there any way I can request the value of the attribute in the fourth tag regardless of what the tag is or what comes before or after it?
Any help would be appreciated -- thanks!
Edit - I didn't write the XML, I request from a remote server.
Upvotes: 1
Views: 172
Reputation: 46
My notes about XML:
Links: http://php.net/simplexml.examples-basic
And example:
$xml='<p4wappremium>
<servermessage>
<providerref sid="123"/>
<useractioninfo
msisdn="48790300200"
tid="12123123"
stid="123123"
pid="345345"
bid="1"
/>
</servermessage>
</p4wappremium>';
$xml = simplexml_load_string($xml);
foreach ($xml->providerref[0]->attributes() as $name -> $value) {
${$name}=$value;
}
foreach ($xml->useractioninfo[0]->attributes() as $name -> $value) {
${$name}=$value;
}
Hope it will be useful for your case.
Upvotes: 2
Reputation: 20045
Well I would suggest you reorganize your "schema". Cause this looks pretty odd to me to associate tag-values by order, like you do.
why not
<Person fname="Mike" lname="Jackson" value="60"/>
or
<Person fname="Mike" lname="Jackson">
<value no="60"/>
</Person>
instead?
Actually the way you apply those tags doesn't seem to be useful or maybe even not valid XML. B/c what you try to parse isn't an xml-dom-tree but a mere list. so why not write a list-parser yourself?
And if you want to use the DOM-extension and getElementsByTagName() then according to the manual you will get a DOMNodeList-object which allows you to refer to the resulting nodes by an index!?
Upvotes: 2