解析php中的xml文件[复制]

时间:2022-12-01 13:06:22

This question already has an answer here:

这个问题在这里已有答案:

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

我有一个xml文件,包含国家名称及其代码。

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

现在我使用以下php代码将它们存储在数组中并打印它们(country.xml文件与此php代码位于同一文件夹中。

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

但这个PHP代码显示空白页面。任何人都可以指导我在哪里犯错误并帮助我纠正它或提供一些更好的方法来解析xml文件。

1 个解决方案

#1


0  

The simplexml_load_file() in PHP will do the job.

PHP中的simplexml_load_file()将完成这项工作。

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

?>

#1


0  

The simplexml_load_file() in PHP will do the job.

PHP中的simplexml_load_file()将完成这项工作。

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

?>