1

I have a xml with below info;

<item>
<site>Cambodia</site> 
<city>Phnom Penh</city> 
<code>21000</code >
</item>

I want to get all the info from this xml and input them into array $data, then echo them one by one like this; site = Cambodia; city = Phnom Penh; code = 21000; but i don't know how to do it. Please help me to solve this problem.

TapiYuki
  • 75
  • 1
  • 1
  • 7

3 Answers3

1

You should be able to just cast it to an array.

$data = new SimpleXMLElement($xml);
$array = (array) $data;
Rob
  • 12,659
  • 4
  • 39
  • 56
0

This might do the trick!

Using xml_parse_into_struct — Parse XML data into an array structure

<?php
     $simple = "<item><site>Cambodia</site><city>Phnom Penh</city><code>21000</code>           </item>";

     $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);
?>

OR SimpleXMLElement

$xml = new SimpleXMLElement($xmlString);

echo $xml->item->site;

$userArray = (array) $xml;
print_r($userArray)
Digital Alchemist
  • 2,324
  • 1
  • 15
  • 17
0

you will get your desired output by the following code

 $xml = '
    <item>
    <site>Cambodia</site> 
    <city>Phnom Penh</city> 
    <code>21000</code >
    </item>';


    $data = new SimpleXmlElement($xml);
     $array = (array) $data;

     foreach($array as $key => $value){
     echo $key .'='. $value.'; ';  ///output:- site = Cambodia; city = Phnom Penh; code = 21000;
     }
user2092317
  • 3,226
  • 5
  • 24
  • 35