문제

i need to read xml file content to php array

this is my xml file :

<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>

i use this:

$xml= simplexml_load_file('filename.xml');

reult is:

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 ) ) ) 

but i need an array like this:

$xml[0]['firstname'] -> 1
$xml[0]['lastname'] -> 2 
......
도움이 되었습니까?

해결책

for an easy xml structure you can use something like this

$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

hope it helps

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top