从XML&amp ;;加载页面特定的子项PHP

时间:2015-01-14 13:33:54

标签: php xml xml-parsing

我有一个xml文件,其中根据url中定义的id显示信息。例如,如果id = vladivostok school-parser.php?id=vladivostok,则会显示以下信息:

Vladivostok University
Vladivostok
Russia
Russian

来自这个xml文件:

<schools>
    <school type="vladivostok">
        <name>Vladivostok University</name>
        <city>Vladivostok</city>
        <country>Russia</country>
        <language>Russian</language>
    </school>
    <school type="florianapolis">
        <name>Florianapolis University</name>
        <city>Florianapolis</city>
        <country>Brazil</country>
        <language>Portuguese</language>
    </school>
    <school type="gatineau">
        <name>Gatineau University</name>
        <city>Gatineau</city>
        <country>Canada</country>
        <language>French</language>
    </school>
</schools>

目前,显示名称,城市,国家和语言。我想只显示四个中的一个或两个,但不一定全部四个。这是我的PHP代码:

$id = $_GET['id'];
$xml = simplexml_load_file('schools.xml');

foreach($xml->children() as $child) {  
   $role = $child->attributes();
   foreach($child as $key => $value) {           
       if($role == $id) {
            echo $value . "<br />";
       }            
   }
}

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

$string = '<schools>
    <school type="vladivostok">
        <name>Vladivostok University</name>
        <city>Vladivostok</city>
        <country>Russia</country>
        <language>Russian</language>
    </school>
    <school type="florianapolis">
        <name>Florianapolis University</name>
        <city>Florianapolis</city>
        <country>Brazil</country>
        <language>Portuguese</language>
    </school>
    <school type="gatineau">
        <name>Gatineau University</name>
        <city>Gatineau</city>
        <country>Canada</country>
        <language>French</language>
    </school>
</schools>';

//$id = $_GET['id'];
//$xml = simplexml_load_file('schools.xml');

$xml = new SimpleXMLElement($string);//test
$id = 'florianapolis';//test

foreach($xml->school as $key=>$data) { 
    if(strtolower($id) == strtolower($data['type'])){
        echo $key.' name:'.$data->name.' city:'.$data->city.' country:'.$data->country.' language:'.$data->language.'<br/>';
    }

}