我需要显示来自文件XML(https://pogoda.yandex.ru/static/cities.xml)的数据PHP数组。我想在数组中所有“id”。帮我找到错误。感谢
<?php
$data_file_city="https://pogoda.yandex.ru/static/cities.xml";
$xml_city = simplexml_load_file($data_file_city);
foreach($xml_city->country as $key=>$value){
foreach ($value->city as $key1=>$value1) {
$id = array("$value1[country]");
echo $id;
}
}
答案 0 :(得分:0)
$value1
中的每个foreach
都是带有属性的SimpleXMLElement对象。
要获取此类对象的属性,请使用attributes
函数:
$ids = array();
$countries = array();
foreach($xml_city->country as $key=>$value){
foreach ($value->city as $key1=>$value1) {
$attrs = $value1->attributes();
// Use `strval` function to cast attribute value to `string` type
// get `id` attribute
$id = strval($attrs['id']);
// get `country` attribute
$country = strval($attrs['country']);
echo $id, '<br />', $country;
// add to array
$ids[] = $id;
$countries[] = $country;
}
}