我想把下面的XML转换成PHP数组。有什么建议吗?

<aaaa Version="1.0">
   <bbb>
     <cccc>
       <dddd Id="id:pass" />
       <eeee name="hearaman" age="24" />
     </cccc>
   </bbb>
</aaaa>

当前回答

我喜欢这个问题,一些答案对我很有帮助,但我需要将xml转换为一个支配数组,所以我将发布我的解决方案,也许以后有人需要它:

<?php
$xml = json_decode(json_encode((array)simplexml_load_string($xml)),1);
$finalItem = getChild($xml);
var_dump($finalItem);

function getChild($xml, $finalItem = []){
    foreach($xml as $key=>$value){
        if(!is_array($value)){
            $finalItem[$key] = $value;
        }else{
            $finalItem = getChild($value, $finalItem);
        }
    }
    return $finalItem;
}
?>  

其他回答

奇怪的是没有人提到xml_parse_into_struct:

$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);

/* Creating an XML file (Optional): Create an XML file which need to convert into the array. test.xml */ <aaaa Version="1.0"> <bbb> <cccc> <dddd Id="id:pass" /> <eeee name="hearaman" age="24" /> </cccc> </bbb> </aaaa> <?php // xml file path $path = "text.xml"; // set your according path for dynamic. // Read entire file into string $xmlfile = file_get_contents($path); // Convert xml string into an object $new = simplexml_load_string($xmlfile); // Convert into json $con = json_encode($new); // Convert into associative array $newArr = json_decode($con, true); print_r($newArr); ?> Output: Result of XML conversion to PHP Array [ 'aaaa' => [ 'bbb' => [ 'cccc' => [ 'dddd' => [ '@value' => '', '@attributes' => [ 'Id' => 'id:pass', ], ], 'eeee' => [ '@value' => '', '@attributes' => [ 'name' => 'hearaman', 'age' => '24', ], ], ], ], '@attributes' => [ 'Version' => '1.0', ], ], ]

$array = json_decode(json_encode((array)simplexml_load_string($xml)),true);

两行代码(https://www.php.net/manual/en/book.simplexml.php#113485)

$xml = new SimpleXMLElement("<your><xml><string>ok</string></xml></your>");
$array = (array)$xml;

简单!

$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);