1

UPD code: "Parse error: syntax error, unexpected '[' in E"

I need to find the array element value on the key value, which is obtained from a variable. In my code somewhere error. Can you help me please? Thanks!

$city_file = 'https://pogoda.yandex.ru/static/cities.xml';   
$xml_city = simplexml_load_file($city_file); 
$cityName = 'Киев';

foreach($xml_city->country as $country){
  foreach($country->city as $city):
    $attrs = $city->attributes();
    $city = strval($city);
    $id = strval($attrs['id']);
    $cities = [];
    $cities [] = [$id=>$city];
  endforeach;
}
$cityid = array_search($cityName, $cities);
echo $cities;
echo $cityid;

UPD 2: Thanks for all, this version is works

    $city_file = 'https://pogoda.yandex.ru/static/cities.xml';   
$xml_city = simplexml_load_file($city_file); 
$cityName = 'Осака';
//$cities = []; - Syntax error
foreach($xml_city->country as $country){
  foreach($country->city as $city):
    $attrs = $city->attributes();
    $city = strval($city);
    $id = strval($attrs['id']);    
    $cities [$id] = $city;
  endforeach;
}

$cityid = array_search($cityName, $cities);
echo $cityid;
I.Swen
  • 61
  • 1
  • 8

1 Answers1

2

Define

   $cities = [];

And below fix this:

  $cities [] = [$id=>$city];

Updated:

  $city_file = 'https://pogoda.yandex.ru/static/cities.xml';   
  $xml_city = simplexml_load_file($city_file); 
  $cityName = 'Киев';
  $cities = [];
 foreach($xml_city->country as $country){
  foreach($country->city as $city):
   $attrs = $city->attributes();
   $city = strval($city);
   $id = strval($attrs['id']);

   $cities [] = [$id=>$city];
  endforeach;
}
$cityid = array_search($cityName, $cities);
print_r($cities);

Update 2:

OK I manually ran the code and still there was an error. And now here is the complete code:

  $city_file = 'https://pogoda.yandex.ru/static/cities.xml';   
  $xml_city = simplexml_load_file($city_file); 
  $cityName = 'Киев';
  $cities = [];
  foreach($xml_city->country as $country){
    foreach($country->city as $city):
      $attrs = $city->attributes();
      $city = strval($city);
      $id = strval($attrs['id']);

      $cities [$id] = $city;
    endforeach;
  }
  $cityid = array_search($cityName, $cities);
  print_r($cities[$cityid]);

Hope it helps.

Kinshuk Lahiri
  • 1,468
  • 10
  • 23