Is there a way i can get a specific item with SimpleXML ?
For example, i would like to get the title of an item having ID set to 12437 with this example xml :
<items>
<item>
<title>blah blah 43534</title>
<id>43534</id>
</item>
<item>
<title>blah blah 12437</title>
<id>12437</id>
</item>
<item>
<title>blah blah 7868</title>
<id>7868</id>
</item>
</items>
Here are 2 simple ways of doing what you want, one is iterating with each item like this:
Live DEMO.
The other would be using an XPath, to pin point the exact data you want like this:
Live DEMO.
You want to use Xpath for this. It's basically exactly the same as outlined in SimpleXML: Selecting Elements Which Have A Certain Attribute Value but in your case you're not deciding on an attribute value but on an element value.
However in Xpath for both the element you're looking for is the parent.So formulating the xpath expression is kind of straight forward:
Output (beautified):
So let's see the heart of this xpath query again:
It's written as: Select all
<item>
elements that are a children of any<items>
elements which on their own have a child element named<id>
with the value"12437"
.And now with the missing stuff around:
The parenthesis around says: From all these
<item>
elements, pick the first one only. Depending on your structure this might or might not be necessary.So here is the full usage example and online demo:
So what you call a field in your questions title is by the book a child-element. Keep this in mind when searching for more complicated xpath queries that get you what you're looking for.