Jim
Jim

Reputation: 1315

get the value of an XML attribute using php

I am attempting to take a value from an attribute and use it in an array to insert it into a MySQL table. My XML file is:

    <?xml version="1.0"?>
<GetMatchingProductForIdResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetMatchingProductForIdResult Id="9780596515898" IdType="ISBN" status="Success">
<Products xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
<Product>
  <Identifiers>
    <MarketplaceASIN>
      <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
      <ASIN>B0026OR39Y</ASIN>
    </MarketplaceASIN>
  </Identifiers>

and using php I need to extract out the value of Id in GetMatchingProductForIdResult. So far my code is this:

    $parsed_xml = ProductId_xml($isbn);
    $isbn13 =(string)$parsed_xml->GetMatchingProductProductForIdResult[0]->attributes();
echo $isbn13['Id']; die;

I am getting no result from the echo statement, even if I change it to print_r or var_dump. I have also tried:

    $amazonResult = array(
                            'isbn' => $parsed_xml->GetMatchingProductProductForIdResult[0]['Id'],

Which yielded no results either. I am not sure where to go from here and any assistance will be greatly appreciated.

EDIT: To clarify this a little bit, the value in Id will change for each record. So what is "9780596515898" this time could be Id="9780596312674" for the next record. I need to know what each one is so I can insert them into the database with the other information I need.

Upvotes: 0

Views: 329

Answers (1)

nickhar
nickhar

Reputation: 20833

I can access the attributes if I close out the XML - otherwise all it does is throw errors. You can access all attributes, or individually through simplexml:

$str = <<<XML
<?xml version="1.0"?>
<GetMatchingProductForIdResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetMatchingProductForIdResult Id="9780596515898" IdType="ISBN" status="Success">
<Products xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
<Product>
  <Identifiers>
    <MarketplaceASIN>
      <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
      <ASIN>B0026OR39Y</ASIN>
    </MarketplaceASIN>
  </Identifiers>
</Product>
</Products>
</GetMatchingProductForIdResult>
</GetMatchingProductForIdResponse>
XML;


$xml = simplexml_load_string($str);

foreach($xml->GetMatchingProductForIdResult->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}

// Or access them directly:

echo $xml->GetMatchingProductForIdResult->attributes()->Id;

Outputs:

Id="9780596515898" IdType="ISBN" status="Success" 9780596515898

Upvotes: 1

Related Questions