2013-03-21 89 views
2

我嘗試將簡單的xml文件轉換爲數組,但轉換不會將「id」屬性保留爲關鍵數組。 XML源:如何將具有屬性的XML文件轉換爲數組

<mapi> 
    <categoriesList> 
     <category id="310">Autres</category> 
     <category id="574">Bière</category> 
     <category id="495">Biscuits</category> 
     <category id="444">Bonbons</category> 
     <category id="435">Champagne</category> 
     <category id="371">Cidre</category> 
     <category id="215">Condiments</category> 
     <category id="8">Fruits</category> 
     <category id="445">Poissons</category> 
     <category id="578">Produits laitiers</category> 
     <category id="539">Spiritueux</category> 
     <category id="259">Viandes</category> 
     <category id="126">Vin</category> 
    </categoriesList> 
</mapi> 

標識是一個簡單的排列是這樣的:

array (
    [310] => Autres 
    [574] => Bière 
    [495] => Biscuits 
    [444] => Bonbons 
    [435] => Champagne 
    [371] => Cidre 
    [215] => Condiments 
    [8] => Fruits 
    [445] => Poissons 
    [578] => Produits laitiers 
    [539] => Spiritueux 
    [259] => Viandes 
    [126] => Vin 
) 

感謝您的幫助 迪米特里

+0

哪裏是你的代碼?你嘗試了什麼? – Uby 2013-03-21 18:07:57

回答

1

像這樣的東西應該工作:

function XMLtoArray($xml) { 
    $xmlArray = array(); 
    $dom = new DOMDocument; 
    $dom->load($xml); 
    $categories = $dom->getElementsByTagName("category"); 
    foreach($categories as $category) { 
     $id = $category->getAttribute("id"); 
     $xmlArray[$id] = $category->nodeValue; 
    } 
    return($xmlArray); 
} 

然後像這樣調用函數:

$myArray = XMLtoArray("path/to/file.xml"); 
+0

完美地工作:-)。謝謝。 – 2013-03-21 18:54:06

+0

不是問題;如果您願意,可以隨意選擇這個答案作爲答案。 – faino 2013-03-21 18:59:26

0
<?php 
    include ("htmlparser.php"); 
    $string = ' 
<mapi> 
    <categoriesList> 
     <category id="310">Autres</category> 
     <category id="574">Bière</category> 
     <category id="495">Biscuits</category> 
     <category id="444">Bonbons</category> 
     <category id="435">Champagne</category> 
     <category id="371">Cidre</category> 
     <category id="215">Condiments</category> 
     <category id="8">Fruits</category> 
     <category id="445">Poissons</category> 
     <category id="578">Produits laitiers</category> 
     <category id="539">Spiritueux</category> 
     <category id="259">Viandes</category> 
     <category id="126">Vin</category> 
    </categoriesList> 
</mapi> 
'; 
$html = str_get_html($string); 
    foreach($html->find('category') as $element){ 
    $array[] = $element -> innertext ; 
    } 

    echo '<pre>'; 
    print_r($array); 
?> 

您需要下載這個庫:http://simplehtmldom.sourceforge.net/manual.htm#section_dump

0

這是一個非常簡單的任務與SimpleXMLElement

$sxe = simplexml_load_string($xml); 
$asarray = array(); 
foreach ($sxe->categoriesList->category as $c) { 
    $asarray[(int) $c['id']] = (string) $c; 
} 

var_export($asarray);