Php 如何将具有属性的XML文件转换为数组
我尝试将一个简单的xml文件转换为一个数组,但转换并没有将“id”属性保留为键数组。 XML来源:Php 如何将具有属性的XML文件转换为数组,php,xml,arrays,Php,Xml,Arrays,我尝试将一个简单的xml文件转换为一个数组,但转换并没有将“id”属性保留为键数组。 XML来源: <mapi> <categoriesList> <category id="310">Autres</category> <category id="574">Bière</category> <category id="495">Biscuits</c
<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>
谢谢你的帮助
Dimitri类似的方法应该会奏效:
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");
您需要下载此库:这是一项非常简单的任务,包括:
你的密码在哪里?你试了什么?效果很好:-)。谢谢,没问题;如果你愿意,请随意选择这个作为答案。
$myArray = XMLtoArray("path/to/file.xml");
<?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);
?>
$sxe = simplexml_load_string($xml);
$asarray = array();
foreach ($sxe->categoriesList->category as $c) {
$asarray[(int) $c['id']] = (string) $c;
}
var_export($asarray);