Solved

XML to ARRAY using PHP

Posted on 2014-03-19
11
766 Views
Last Modified: 2014-03-23
Hello I have script that returns XML...I tried to covert it into an array. It works mostly, but when I try to loop part of the array since the array can have multiple items it seems as though the array is broken up in to 4 parts...

So here is what I have..When I do a var_dump on the original data sent back I get this

object(SimpleXMLElement)#27 (3) {
  ["@attributes"]=>
  array(3) {
    ["timestamp"]=>
    string(25) "2014-03-19T15:31:55-05:00"
    ["payloadID"]=>
    string(81) "2014-03-19T15:31:55-05:00.WC@vOmAl/S8yzyHUc6egkAxb8Xi0co= .9123001443@42374153835"
    ["version"]=>
    string(7) "1.2.008"
  }
  ["Header"]=>
  object(SimpleXMLElement)#36 (3) {
    ["From"]=>
    object(SimpleXMLElement)#38 (1) {
      ["Credential"]=>
      object(SimpleXMLElement)#41 (2) {
        ["@attributes"]=>
        array(1) {
          ["domain"]=>
          string(4) "DUNS"
        }
        ["Identity"]=>
        string(9) "079928354"
      }
    }
    ["To"]=>
    object(SimpleXMLElement)#39 (1) {
      ["Credential"]=>
      object(SimpleXMLElement)#41 (2) {
        ["@attributes"]=>
        array(1) {
          ["domain"]=>
          string(9) "NetworkID"
        }
        ["Identity"]=>
        string(7) "DICERNA"
      }
    }
    ["Sender"]=>
    object(SimpleXMLElement)#40 (2) {
      ["Credential"]=>
      object(SimpleXMLElement)#41 (2) {
        ["@attributes"]=>
        array(1) {
          ["domain"]=>
          string(9) "NetworkID"
        }
        ["Identity"]=>
        string(10) "BELLWETHER"
      }
      ["UserAgent"]=>
      object(SimpleXMLElement)#42 (0) {
      }
    }
  }
  ["Message"]=>
  object(SimpleXMLElement)#37 (1) {
    ["PunchOutOrderMessage"]=>
    object(SimpleXMLElement)#40 (3) {
      ["BuyerCookie"]=>
      string(28) "Tue05thNov2013122808WendyCyr"
      ["PunchOutOrderMessageHeader"]=>
      object(SimpleXMLElement)#39 (4) {
        ["@attributes"]=>
        array(1) {
          ["operationAllowed"]=>
          string(4) "edit"
        }
        ["Total"]=>
        object(SimpleXMLElement)#42 (1) {
          ["Money"]=>
          string(6) "353.09"
        }
        ["Shipping"]=>
        object(SimpleXMLElement)#41 (2) {
          ["Money"]=>
          string(5) "47.09"
          ["Description"]=>
          object(SimpleXMLElement)#44 (1) {
            ["ShortName"]=>
            string(41) "Shipping Method Is Indicated by Line Item"
          }
        }
        ["Tax"]=>
        object(SimpleXMLElement)#43 (2) {
          ["Money"]=>
          string(1) "0"
          ["Description"]=>
          object(SimpleXMLElement)#44 (0) {
          }
        }
      }
      ["ItemIn"]=>
      object(SimpleXMLElement)#38 (4) {
        ["@attributes"]=>
        array(1) {
          ["quantity"]=>
          string(1) "3"
        }
        ["ItemID"]=>
        object(SimpleXMLElement)#43 (2) {
          ["SupplierPartID"]=>
          string(11) "D4545-250UN"
          ["SupplierPartAuxiliaryID"]=>
          string(15) "CartId`68533508"
        }
        ["ItemDetail"]=>
        object(SimpleXMLElement)#41 (7) {
          ["UnitPrice"]=>
          object(SimpleXMLElement)#44 (1) {
            ["Money"]=>
            string(6) "102.00"
          }
          ["Description"]=>
          object(SimpleXMLElement)#45 (1) {
            ["ShortName"]=>
            string(40) "TAQ DNA POLYMERASE WITH 10X REACTION   &"
          }
          ["UnitOfMeasure"]=>
          string(2) "EA"
          ["Classification"]=>
          string(8) "12352200"
          ["ManufacturerPartID"]=>
          string(5) "D4545"
          ["ManufacturerName"]=>
          string(5) "SIGMA"
          ["Extrinsic"]=>
          array(17) {
            [0]=>
            string(10) "0009012902"
            [1]=>
            string(10) "0009012902"
            [2]=>
            string(6) "102.00"
            [3]=>
            string(3) "USD"
            [4]=>
            string(1) "C"
            [5]=>
            object(SimpleXMLElement)#46 (1) {
              ["@attributes"]=>
              array(1) {
                ["name"]=>
                string(20) "HazardRegulationCode"
              }
            }
            [6]=>
            object(SimpleXMLElement)#47 (1) {
              ["@attributes"]=>
              array(1) {
                ["name"]=>
                string(6) "CATAPP"
              }
            }
            [7]=>
            object(SimpleXMLElement)#48 (1) {
              ["@attributes"]=>
              array(1) {
                ["name"]=>
                string(20) "ShippingInstructions"
              }
            }
            [8]=>
            string(1) "2"
            [9]=>
            string(1) "2"
            [10]=>
            object(SimpleXMLElement)#49 (1) {
              ["@attributes"]=>
              array(1) {
                ["name"]=>
                string(18) "rd_purchasinggroup"
              }
            }
            [11]=>
            string(8) "12352200"
            [12]=>
            string(1) "1"
            [13]=>
            string(36) "3 In Stock from SAINT LOUIS 03/19/14"
            [14]=>
            string(1) "3"
            [15]=>
            object(SimpleXMLElement)#50 (1) {
              ["@attributes"]=>
              array(1) {
                ["name"]=>
                string(10) "QtyPending"
              }
            }
            [16]=>
            string(68) "http://www.sigmaaldrich.com/catalog/search/ProductDetail/SIGMA/D4545"
          }
        }
        ["Shipping"]=>
        object(SimpleXMLElement)#42 (2) {
          ["Money"]=>
          string(1) "0"
          ["Description"]=>
          object(SimpleXMLElement)#50 (1) {
            ["ShortName"]=>
            string(15) "FEDEX OVERNIGHT"
          }
        }
      }
    }
  }
}

Open in new window


After I get this code I convert it to an array using

$array = json_decode(json_encode((array) $xml), 1);
$array = array($xml->getName() => $array);

Open in new window



I can then pull out each variable...But the problem lines when I get to

foreach($array['cXML']['Message']['PunchOutOrderMessage']['ItemIn']  as $item)
{
}

Open in new window


if I do a print_r($item); inside the loop it returns 4 separate arrays..Any ideas why it is not one array and how I can fix this?

Thanks!
0
Comment
Question by:bradley525
  • 7
  • 4
11 Comments
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39940922
Please post the original XML document.  You can obscure passwords or any private information like that, but I would need the structure (and tag names) to be intact.  I'll show you how to parse it.  Thanks, ~Ray
0
 

Author Comment

by:bradley525
ID: 39940936
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.2.008/cXML.dtd"><cXML xml:lang="en-US" timestamp="2014-03-19T15:31:55-05:00" payloadID="2014-03-19T15:31:55-05:00.WC@vOmAl/S8yzyHUc6egkAxb8Xi0co= .9123001443@42374153835" version="1.2.008"><Header><From><Credential domain="DUNS"><Identity>079928354</Identity></Credential></From><To><Credential domain="NetworkID"><Identity>DICERNA</Identity></Credential></To><Sender><Credential domain="NetworkID"><Identity>BELLWETHER</Identity></Credential><UserAgent/></Sender></Header><Message><PunchOutOrderMessage><BuyerCookie>Tue05thNov2013122808WendyCyr</BuyerCookie><PunchOutOrderMessageHeader operationAllowed="edit"><Total><Money currency="USD">353.09</Money></Total><Shipping><Money currency="USD">47.09</Money><Description xml:lang="en-US"><ShortName>Shipping Method Is Indicated by Line Item</ShortName></Description></Shipping><Tax><Money currency="USD">0</Money><Description xml:lang="en-US"/></Tax></PunchOutOrderMessageHeader><ItemIn quantity="3"><ItemID><SupplierPartID>D4545-250UN</SupplierPartID><SupplierPartAuxiliaryID>CartId`68533508</SupplierPartAuxiliaryID></ItemID><ItemDetail><UnitPrice><Money currency="USD">102.00</Money></UnitPrice><Description xml:lang="en-US"><ShortName>TAQ DNA POLYMERASE WITH 10X REACTION   &amp;</ShortName>TAQ DNA POLYMERASE WITH 10X REACTION   &amp;</Description><UnitOfMeasure>EA</UnitOfMeasure><Classification domain="UNSPSC">12352200</Classification><ManufacturerPartID>D4545</ManufacturerPartID><ManufacturerName>SIGMA</ManufacturerName><Extrinsic name="CAS Number">0009012902</Extrinsic><Extrinsic name="ZChCas">0009012902</Extrinsic><Extrinsic name="MarketPrice">102.00</Extrinsic><Extrinsic name="MarketPriceCurrency">USD</Extrinsic><Extrinsic name="HazardClass">C</Extrinsic><Extrinsic name="HazardRegulationCode"/><Extrinsic name="CATAPP"/><Extrinsic name="ShippingInstructions"/><Extrinsic name="LeadTime">2</Extrinsic><Extrinsic name="StandardLeadTime">2</Extrinsic><Extrinsic name="rd_purchasinggroup"/><Extrinsic name="CommCode">12352200</Extrinsic><Extrinsic name="PkgQuantity">1</Extrinsic><Extrinsic name="availabilityPhrase">3 In Stock from SAINT LOUIS 03/19/14</Extrinsic><Extrinsic name="QtyAvailable">3</Extrinsic><Extrinsic name="QtyPending"/><Extrinsic name="Product Information Page URL">http://www.sigmaaldrich.com/catalog/search/ProductDetail/SIGMA/D4545</Extrinsic></ItemDetail><Shipping><Money currency="USD">0</Money><Description xml:lang="en-US"><ShortName>FEDEX OVERNIGHT</ShortName></Description></Shipping></ItemIn></PunchOutOrderMessage></Message></cXML>

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39940940
Thanks, back in a moment....
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39940969
Hmm... It does not quite look that way to me.  Have a look at this:
http://iconoun.com/demo/temp_bradley525.php

<?php // demo/bradley525.php
error_reporting(E_ALL);
echo '<pre>';

// SEE: http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28392665.html

// TEST DATA FROM THE POST AT EE SHOWN IN HEREDOC NOTATION
$xml = <<<ENDXML
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.2.008/cXML.dtd"><cXML xml:lang="en-US" timestamp="2014-03-19T15:31:55-05:00" payloadID="2014-03-19T15:31:55-05:00.WC@vOmAl/S8yzyHUc6egkAxb8Xi0co= .9123001443@42374153835" version="1.2.008"><Header><From><Credential domain="DUNS"><Identity>079928354</Identity></Credential></From><To><Credential domain="NetworkID"><Identity>DICERNA</Identity></Credential></To><Sender><Credential domain="NetworkID"><Identity>BELLWETHER</Identity></Credential><UserAgent/></Sender></Header><Message><PunchOutOrderMessage><BuyerCookie>Tue05thNov2013122808WendyCyr</BuyerCookie><PunchOutOrderMessageHeader operationAllowed="edit"><Total><Money currency="USD">353.09</Money></Total><Shipping><Money currency="USD">47.09</Money><Description xml:lang="en-US"><ShortName>Shipping Method Is Indicated by Line Item</ShortName></Description></Shipping><Tax><Money currency="USD">0</Money><Description xml:lang="en-US"/></Tax></PunchOutOrderMessageHeader><ItemIn quantity="3"><ItemID><SupplierPartID>D4545-250UN</SupplierPartID><SupplierPartAuxiliaryID>CartId`68533508</SupplierPartAuxiliaryID></ItemID><ItemDetail><UnitPrice><Money currency="USD">102.00</Money></UnitPrice><Description xml:lang="en-US"><ShortName>TAQ DNA POLYMERASE WITH 10X REACTION   &amp;</ShortName>TAQ DNA POLYMERASE WITH 10X REACTION   &amp;</Description><UnitOfMeasure>EA</UnitOfMeasure><Classification domain="UNSPSC">12352200</Classification><ManufacturerPartID>D4545</ManufacturerPartID><ManufacturerName>SIGMA</ManufacturerName><Extrinsic name="CAS Number">0009012902</Extrinsic><Extrinsic name="ZChCas">0009012902</Extrinsic><Extrinsic name="MarketPrice">102.00</Extrinsic><Extrinsic name="MarketPriceCurrency">USD</Extrinsic><Extrinsic name="HazardClass">C</Extrinsic><Extrinsic name="HazardRegulationCode"/><Extrinsic name="CATAPP"/><Extrinsic name="ShippingInstructions"/><Extrinsic name="LeadTime">2</Extrinsic><Extrinsic name="StandardLeadTime">2</Extrinsic><Extrinsic name="rd_purchasinggroup"/><Extrinsic name="CommCode">12352200</Extrinsic><Extrinsic name="PkgQuantity">1</Extrinsic><Extrinsic name="availabilityPhrase">3 In Stock from SAINT LOUIS 03/19/14</Extrinsic><Extrinsic name="QtyAvailable">3</Extrinsic><Extrinsic name="QtyPending"/><Extrinsic name="Product Information Page URL">http://www.sigmaaldrich.com/catalog/search/ProductDetail/SIGMA/D4545</Extrinsic></ItemDetail><Shipping><Money currency="USD">0</Money><Description xml:lang="en-US"><ShortName>FEDEX OVERNIGHT</ShortName></Description></Shipping></ItemIn></PunchOutOrderMessage></Message></cXML>
ENDXML;

// MAKE AN OBJECT
$obj = SimpleXML_Load_string($xml);

// ACTIVATE THIS TO SEE THE OBJECT
// print_r($obj);

$item = $obj->Message->PunchOutOrderMessage->ItemIn;
print_r($item);

Open in new window

0
 

Author Comment

by:bradley525
ID: 39941996
This does work, but I already had this working..What I am trying to do is loop through the items...

I added
$array = json_decode(json_encode((array)$item), TRUE);
print_r($item);

Open in new window


to the end of your code to convert it into an array...But I still cant loop through 'ItemIn' I am trying to do a foreach loop but it errors out each time..

Thanks
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39942032
it errors out each time
Exactly what output do you get?
loop through the items
But there is only one item!  It's an object - a data structure with stuff inside it.  Are you aiming to get the contents of the data structure?  Or is the test data missing some other items?  Please clarify and I'll try to get you a better code example, thanks.
0
 

Author Comment

by:bradley525
ID: 39942122
Actually I was able to get it to work by

oreach($item as $itm)
{
echo $itm->ItemID[0]->SupplierPartID;
}

Open in new window


But in the xml there is a ['@attributes'] and I am not sure how to handle this?

I was trying

echo $itm->ItemDetail[0]->Extrinsic[5]->@attributes->name;

Open in new window


but i receive and error..
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39942286
This turns into a mess when you get to the Extrinsic components.  Do you have any influence over the format of the XML document?  If so, it might make a lot of sense to wrap the Extrinsic elements in an <Extrinsics> tag.

Still working it, but I get the feeling that it's not a straightforward solution!
0
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39942315
This seems to work.  Usually var_dump() is your friend, but it didn't produce what I expected here.  Moving parts to extract the Extrinsic components start at line 60.  

I reformatted the XML document a little bit so I could see what I was working with, since var_dump() was not as helpful as I hoped.  The reformatting has no effect on the execution of the script.

<?php // demo/bradley525.php
error_reporting(E_ALL);
echo '<pre>';

// SEE: http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28392665.html

// TEST DATA FROM THE POST AT EE SHOWN IN HEREDOC NOTATION
$xml = <<<ENDXML
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.2.008/cXML.dtd"><cXML xml:lang="en-US" timestamp="2014-03-19T15:31:55-05:00" payloadID="2014-03-19T15:31:55-05:00.WC@vOmAl/S8yzyHUc6egkAxb8Xi0co= .9123001443@42374153835" version="1.2.008"><Header><From><Credential domain="DUNS"><Identity>079928354</Identity></Credential></From><To><Credential domain="NetworkID"><Identity>DICERNA</Identity></Credential></To><Sender><Credential domain="NetworkID"><Identity>BELLWETHER</Identity></Credential><UserAgent/></Sender></Header><Message><PunchOutOrderMessage><BuyerCookie>Tue05thNov2013122808WendyCyr</BuyerCookie><PunchOutOrderMessageHeader operationAllowed="edit"><Total><Money currency="USD">353.09</Money></Total><Shipping><Money currency="USD">47.09</Money><Description xml:lang="en-US"><ShortName>Shipping Method Is Indicated by Line Item</ShortName></Description></Shipping><Tax><Money currency="USD">0</Money><Description xml:lang="en-US"/></Tax></PunchOutOrderMessageHeader><ItemIn quantity="3"><ItemID><SupplierPartID>D4545-250UN</SupplierPartID><SupplierPartAuxiliaryID>CartId`68533508</SupplierPartAuxiliaryID></ItemID><ItemDetail><UnitPrice><Money currency="USD">102.00</Money></UnitPrice><Description xml:lang="en-US"><ShortName>TAQ DNA POLYMERASE WITH 10X REACTION   &amp;</ShortName>TAQ DNA POLYMERASE WITH 10X REACTION   &amp;</Description><UnitOfMeasure>EA</UnitOfMeasure><Classification domain="UNSPSC">12352200</Classification><ManufacturerPartID>D4545</ManufacturerPartID><ManufacturerName>SIGMA</ManufacturerName>
<Extrinsic name="CAS Number">0009012902</Extrinsic>
<Extrinsic name="ZChCas">0009012902</Extrinsic>
<Extrinsic name="MarketPrice">102.00</Extrinsic>
<Extrinsic name="MarketPriceCurrency">USD</Extrinsic>
<Extrinsic name="HazardClass">C</Extrinsic>
<Extrinsic name="HazardRegulationCode"/>
<Extrinsic name="CATAPP"/>
<Extrinsic name="ShippingInstructions"/>
<Extrinsic name="LeadTime">2</Extrinsic>
<Extrinsic name="StandardLeadTime">2</Extrinsic>
<Extrinsic name="rd_purchasinggroup"/>
<Extrinsic name="CommCode">12352200</Extrinsic>
<Extrinsic name="PkgQuantity">1</Extrinsic>
<Extrinsic name="availabilityPhrase">3 In Stock from SAINT LOUIS 03/19/14</Extrinsic>
<Extrinsic name="QtyAvailable">3</Extrinsic>
<Extrinsic name="QtyPending"/>
<Extrinsic name="Product Information Page URL">http://www.sigmaaldrich.com/catalog/search/ProductDetail/SIGMA/D4545</Extrinsic>
</ItemDetail><Shipping><Money currency="USD">0</Money><Description xml:lang="en-US"><ShortName>FEDEX OVERNIGHT</ShortName></Description></Shipping></ItemIn></PunchOutOrderMessage></Message></cXML>
ENDXML;

// MAKE AN OBJECT
$obj = SimpleXML_Load_string($xml);

// ACTIVATE THIS TO SEE THE OBJECT
// var_dump($obj);

// EXTRACT THE ITEM DATA
$item = $obj->Message->PunchOutOrderMessage->ItemIn;

// ACTIVATE THIS TO SEE THE ITEM DATA
// var_dump($item);

// SHOW ATTRIBUTES
$attr = $item->attributes()->quantity;
echo PHP_EOL . "quantity = $attr";

// SHOW SOME INTERNAL DATA
$spid = $item->ItemID->SupplierPartID;
echo PHP_EOL . "SupplierPartID = $spid";

$iupm = $item->ItemDetail->UnitPrice->Money;
echo PHP_EOL . "Unit Price Money = $iupm";

$idds = $item->ItemDetail->Description->ShortName;
echo PHP_EOL . "Short Name = $idds";

echo PHP_EOL;
echo PHP_EOL . "<b>Extrinsic Objects:</b>";

// SHOW THE EXTRINSIC STUFF
foreach ($item->ItemDetail->Extrinsic as $extr)
{
    echo PHP_EOL;
    foreach ($extr->attributes() as $attr)
    {
        // CAST THE DATA TO STRING FORMAT
        $a = (string)$attr;
        $x = (string)$extr;
        if (empty($x)) $x = 'VALUE OMITTED';
        echo "$a ==> $x";
    }
}

Open in new window

HTH, ~Ray
0
 

Author Closing Comment

by:bradley525
ID: 39948984
HI Ray,

This did work perfect..Thank you for your help...Thanks!
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39949015
Glad to help.  Thanks for the points and thanks for using EE, ~Ray
0

Featured Post

How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Split wordpress loop 35 56
PHP and MSSQL Arrays and Variables 3 26
Log in through ID 5 19
Inserting results of While loop to sql server 5 20
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Many times as a report developer I've been asked to display normalized data such as three rows with values Jack, Joe, and Bob as a single comma-separated string such as 'Jack, Joe, Bob', and vice versa.  Here's how to do it. 
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question