PHP中的XML不显示数组

时间:2016-11-13 12:15:36

标签: php xml arr

我需要显示来自文件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;
    }
  }

1 个答案:

答案 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;
    }
}