Search code examples
phpsimplexml

Save array to XML file using SimpleXML


I'm using the code below to sort the content of my XML file by "WebCategory". My question is how do I save the newly sorted $products array back to the XML file?

<?php

$products = array();

$xml = simplexml_load_file('nwgalaxy-edited.xml'); 

foreach($xml->Product as $item) {
    $products[] = array(
        'ProductID' => (string)$item->attributes()->ProductID,
        'Description' => (string)$item->Description,
        'WebCategory' => (string)$item->WebCategory,
        'WebSubCategory' => (string)$item->WebSubCategory,
        'WebSubCat2' => (string)$item->WebSubCat2,
        'QtyOnHand' => intval($item->QtyOnHand),
        'SellingPrice' => intval($item->SellingPrice),
        'ListPrice' => intval($item->ListPrice),
        'NWGalaxy' => intval($item->NWGalaxy),
        'UPC' => intval($item->UPC),
        'VendorProductID' => (string)$item->VendorProductID,
        'ImageSmall' => (string)$item->ImageSmall,
        'ImageLarge' => (string)$item->ImageLarge
    );
}

array_sort_by_column($products, 'WebCategory');

function array_sort_by_column(&$array, $column, $direction = SORT_ASC) {
    $reference_array = array();
    foreach($array as $key => $row) {
        $reference_array[$key] = $row[$column];
    }

    array_multisort($reference_array, $direction, $array);
}

?>

Solution

  • This may work, not tested but should give general idea.

    // Create tag products
    $xml = new SimpleXMLElement('<products/>');
    
    // Walk the array with callback to method $xml->addChild($this)
    array_walk_recursive($products, array($xml, 'addChild'));
    
    // Save generated content to file.
    file_put_contents('nwgalaxy-edited.xml', $xml->asXML());