1

I have an xml file which consist of name of the country and its code.

<country>
    <name>ALBANIA</name>
    <code>AL</code>
</country>

<country>
    <name>ALGERIA</name>
    <code>DZ</code>
</country>

<country>
    <name>AMERICAN SAMOA</name>
    <code>AS</code>
</country>

now I am using following php code to store them in array and printing them(country.xml file is in the same folder as this php code.

$countries = array();
$file = new SimpleXMLElement(__DIR__ . '/country.xml', null, true);
foreach ($file->country as $country) {
        $name = trim($country['name']);
    $code = trim(strtoupper($country['code']));

    $countries[$code] = $name;
    echo $code;
}

but this php code shows blank page. Can anyone guide me where I am making mistake and help me to correct it or give some better method to parse xml file.

prattom
  • 1,625
  • 11
  • 42
  • 67

1 Answers1

0

The simplexml_load_file() in PHP will do the job.

<?php
$xml = simplexml_load_file('country.xml');
$i=0;

$countryName=array();
$countryCode=array();

foreach($xml as $k=>$v)
{
    $countryName[$i] = (string) $xml->country[$i]->name;
    $countryCode[$i] = (string) $xml->country[$i]->code;
$i++;
}

print_r($countryName);
print_r($countryCode);

?>
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126