XML in to a PHP 不显示数组
XML in to a PHP does not display an array
我需要显示文件 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;
}
}
您 foreach
中的每个 $value1
都是具有属性的 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;
}
}
我需要显示文件 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;
}
}
您 foreach
中的每个 $value1
都是具有属性的 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;
}
}