2017-05-22 2 views
0

私のXMLファイルの内容を「WebCategory」でソートするには、以下のコードを使用しています。私の質問は、どのように新しく並べ替えられた$製品配列をXMLファイルに保存するのですか?SimpleXMLを使用して配列を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); 
} 

?> 
+0

check https://stackoverflow.com/questions/7609095/is-there-an-xml-encode-like-json-encode-in-php – hanshenrik

答えて

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()); 
関連する問題