我需要将XML文件内容读取到php数组
这是我的XML文件:
<users>
<user>
<firstname>1</firstname>
<lastname>2</lastname>
<username>3</username>
<password>4</password>
</user>
<user>
<firstname>5</firstname>
<lastname>6</lastname>
<username>7</username>
<password>8</password>
</user>
</users>
我使用这个:
$xml= simplexml_load_file('filename.xml');
结果是:
SimpleXMLElement Object ( [user] => Array ( [0] => SimpleXMLElement Object ( [firstname] => 1 [lastname] => 2 [username] => 3 [password] => 4 ) [1] => SimpleXMLElement Object ( [firstname] => 5 [lastname] => 6 [username] => 7 [password] => 8 ) ) )
但是我需要这样的数组:
$xml[0]['firstname'] -> 1
$xml[0]['lastname'] -> 2
......
对于一个简单的XML结构,你可以使用这样的东西
$xml = '<users>
<user>
<firstname>1</firstname>
<lastname>2</lastname>
<username>3</username>
<password>4</password>
</user>
<user>
<firstname>5</firstname>
<lastname>6</lastname>
<username>7</username>
<password>8</password>
</user>
</users>';
$input_xml = simplexml_load_string($xml); // load the xml string
$json = json_encode($input_xml); // convert to json object
$output_array = json_decode($json, TRUE); // decode the json and transform to an array
希望对您有所帮助