【问题标题】:Save array to XML file using SimpleXML使用 SimpleXML 将数组保存到 XML 文件
【发布时间】:2017-10-22 16:11:39
【问题描述】:

我正在使用下面的代码按“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);
}

?>

【问题讨论】:

标签: php simplexml


【解决方案1】:

这可能有效,未经测试,但应该给出一般的想法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多