PHP Xpath extracting a value for a node with attribute name="author"
Solution 1
Here is the solution. Basically you can make an XPath call off the result node to get all attribute elements with the name attribute equal to author.
Then you check and make sure a result came back, and if it did, it will be index[0] since XPath calls return an array of results. Then you use the attributes()
function to get an associate array of the attribute, finally getting the value you want.
$XML = simplexml_load_string($xml_string);
$XMLResults = $XML->xpath('/GSP/RES/R');
foreach($XMLResults as $Result) {
$Label = $Result->Label;
$AuthorAttribute = $Result->xpath('//Attribute[@name="author"]');
// Make sure there's an author attribute
if($AuthorAttribute) {
// because we have a list of elements even if there's one result
$attributes = $AuthorAttribute[0]->attributes();
$Author = $attributes['value'];
}
else {
// No Author
}
}
Solution 2
$authors = $Result->xpath('PageMap/DataObject/Attribute[@name="author"]');
if (count($authors)) {
$author = (string) $authors[0]['value'];
}
Basic
If you need to contact me, you know what to do... [email protected]
Updated on June 04, 2022Comments
-
Basic almost 2 years
I'm trying to parse some XML data to get the value of a certain attribute - Specifically, I want to find the author. Below is a very cut-down but valid example. The
R
node is repeated multiple times.<GSP VER="3.2"> <RES SN="1" EN="10"> <R N="4" MIME="application/pdf"> <Label>_cse_rvfaxixpaw0</Label> <PageMap> <DataObject type="metatags"> <Attribute name="creationdate" value="D:20021024104222Z"/> <Attribute name="author" value="Diana Van Winkle"/> </DataObject> </PageMap> </R> </RES> </GSP>
Currently I do:
$XML = simplexml_load_string($XMLResult); $XMLResults = $XML->xpath('/GSP/RES/R'); foreach($XMLResults as $Result) { $Label = $Result->Label; $Author = ""; // <-- How do I get this? }
Can someone please explain to me how I can pull out the "author" attribute? The author attribute will be present a maximum of 1 times but may not be present at all (I can handle that myself)
-
Basic almost 13 yearsThanks, that selects the node. Perhaps I was unclear, but how can I select the contents of "value" for that node? Sorry, I'm very new to XPath
-
Basic almost 13 yearsThanks, that worked - Can you please explain why you didn't need to specify the path to the node? Are you just looking for ANY node that have an attribute of
name="author"
? If so, it's fine but I'm just curious. Cheers -
Phil almost 13 years@Basiclife
$author
is set to thevalue
attribute of the first element in the array -
onteria_ almost 13 years@Basiclife Yes, it's looking for any Attribute node with the attribute of
name="author"
from the context of the current<R>
element.