Jump to content

json to simpleXML (PHP)


reldridge
Go to solution Solved by reldridge,

Recommended Posts

I am trying to convert JSON to XML using php.  The json file is part of the Ecwid e-commerce sites api.

http://developers.ecwid.com/api-documentation#orders

 

PHP

<?php
# An HTTP GET request example

$url = 'https://app.ecwid.com/api/v3/{STOREID}/orders?paymentStatus=PAID&fulfillmentStatus=AWAITING_PROCESSING&token={TOKEN}';



$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);

$data = str_replace("<br>", " ", $data);
$json_obj = json_decode($data, true);

var_dump($json_obj);

echo '<br> <br> <br> <br>';
echo '<h1> PHP Array (json_decode)</h1>';

foreach ($json_obj['items'] as $item) {
  echo "<pre>";
    print_r($item);
} 

echo '<br> <br> <br> <br>';
echo '<h1> XML CONVERSION</h1>';

$xml = new SimpleXMLElement('<root/>');
array_flip($xml);
array_walk_recursive($json_obj, array ($xml, 'addChild'));
print $xml->asXML();

?>

The XML is coming out with the keys and values flipped.

I am trying to use array_flip() to fix this but not sure how to get this to work.

 

XML - without array_flip()

<1>total<1>count<0>offset<100>limit<0137062>vendorOrderNumber<79>subtotal<138.65>totalemail<96U34224JE632150D>externalTransactionIdpaymentModulepaymentMethod<0>tax<80.217.64.221>ipAddress<0>couponDiscounttrackingNumberpaymentStatuspaymentMessagefulfillmentStatus<7062>orderNumberrefererUrlorderComments<0>volumeDiscount<24198510>customerId<0>membershipBasedDiscount<0>totalAndMembershipBasedDiscount<0>discount<138.65>usdTotalglobalReferer<00:20 +0000>createDate<31:09 +0000>updateDate<1452261620>createTimestamp<1452630669>updateTimestamp<69399848>id<51555117>productId<2455976>categoryId<40>price<40>productPrice<00604>sku<1>quantityshortDescription<0>tax<17.289855072464>shipping<23>quantityInStockname<1>isShippingRequired<2>weight<1>trackQuantityimageUrlsmallThumbnailUrl<0>fixedShippingRate<1>productAvailablenamevalue0type<69399849>id<15479536>productId<2455976>categoryId<20>price<20>productPrice<00096>sku<1>quantityshortDescription<0>tax<10.373913043478>shipping<211>quantityInStockname<1>isShippingRequired<1.2>weight<1>trackQuantityimageUrlsmallThumbnailUrl<0>fixedShippingRate<1>productAvailable<69399850>id<37228667>productId<2455976>categoryId<15>price<15>productPrice<30701>sku<1>quantityshortDescription<0>tax<30.257246376812>shipping<104>quantityInStockname<1>isShippingRequired<3.5>weight<1>trackQuantityimageUrlsmallThumbnailUrl<0>fixedShippingRate<1>productAvailablenamevalue0type<69399851>id<46912544>productId<2455976>categoryId<2>price<2>productPrice<00421>sku<1>quantityshortDescription<0>tax<0.86449275362319>shipping<59>quantityInStockname<1>isShippingRequired<0.1>weight<1>trackQuantityimageUrlsmallThumbnailUrl<0>fixedShippingRate<1>productAvailable<69399852>id<46912548>productId<2455976>categoryId<2>price<2>productPrice<00423>sku<1>quantityshortDescription<0>tax<0.86449275362319>shipping<44>quantityInStockname<1>isShippingRequired<0.1>weight<1>trackQuantityimageUrlsmallThumbnailUrl<0>fixedShippingRate<1>productAvailablenamestreetcitycountryCodecountryName<12371>postalCodestateOrProvinceCodestateOrProvinceName<0046707340555>phonenamestreetcitycountryCodecountryName<12371>postalCodestateOrProvinceCodestateOrProvinceName<0046707340555>phoneshippingCarrierNameshippingMethodName<59.65>shippingRate<6-10>estimatedTransitTimename<0>value

Using array_flip() how I have above in the PHP does nothing.

Edited by reldridge
Link to comment
Share on other sites

  • Solution

Using the below function I was able to get the exported xml data to a file in the correct format.

// function to convert multi-dimensional array to xml
function array2XML($obj, $array)
{
    foreach ($array as $key => $value)
    {
        if(is_numeric($key))
            $key = 'item' . $key;

        if (is_array($value))
        {
            $node = $obj->addChild($key);
            array2XML($node, $value);
        }
        else
        {
            $obj->addChild($key, htmlspecialchars($value));
        }
    }
}

$xml = new SimpleXMLElement('<root/>');
array2XML($xml, $json_obj);
echo (($xml->asXML('data.xml')) ? 'Your XML file has been generated successfully!' : 'Error generating XML file!');

//Store data as a string to send to database
//$data = $xml->asXML();
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.