PHP Xpath retrieving value for node with attribute name = "author"

I am trying to parse some XML data to get the value of a specific attribute. In particular, I want to find the author. The following is a very short but valid example. Rnode repeats several 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>

I am currently doing:

$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 attribute "author"? The author’s attribute will be present at most 1 time, but may be absent altogether (I can handle this myself)

+3
source share
2 answers

Here is the solution. Basically, you can make an XPath call to the result of a node to get all attribute elements with a name attribute equal to the author.

, , , [0], XPath . attributes() , , , .

$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 an author attribute
    if($AuthorAttribute) {
      // because we have a list of elements even if there one result
      $attributes = $AuthorAttribute[0]->attributes();
      $Author = $attributes['value'];
    }
    else {
      // No Author
    }
}
+4
$authors = $Result->xpath('PageMap/DataObject/Attribute[@name="author"]');
if (count($authors)) {
    $author = (string) $authors[0]['value'];
}
+2

All Articles