PHP Xpath extracting a value for a node with attri

2020-03-26 00:05发布

问题:

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)

回答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
    }
}


回答2:

$authors = $Result->xpath('PageMap/DataObject/Attribute[@name="author"]');
if (count($authors)) {
    $author = (string) $authors[0]['value'];
}