2

単純なxmlファイルを配列に変換しようとしましたが、変換によって「id」属性がキー配列として保持されません。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
)

助けてくれてありがとうDimitri

4

3 に答える 3

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");
于 2013-03-21T18:18:56.533 に答える
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

于 2013-03-21T18:36:52.707 に答える
0

これは非常に単純なタスクSimpleXMLElementです。

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

var_export($asarray);
于 2013-03-22T17:05:09.833 に答える