使用SimpleXML将数组保存到XML文件

时间:2017-05-22 21:28:03

标签: php simplexml

我使用下面的代码按" WebCategory"对XML文件的内容进行排序。我的问题是如何将新排序的$ products数组保存回XML文件?

<?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);
}

?>

1 个答案:

答案 0 :(得分:0)

这可能有效,未经测试但应该提供一般性的想法。

// 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());