php - 在php中使用foreach循环遍历SimpleXML
问题描述
我正在尝试将数组值放入下一个 SimpleXMLElement 对象以获取 [property] 值,但我不确定在 PHP 中使用 foreach 循环该对象的最佳方法是什么,
我得到的目标代码:
SimpleXMLElement Object
(
[nowplaying-info] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[mountName] => KDLDFMAAC
[timestamp] => 1621880102
[type] => track
)
[property] => Array
(
[0] => 248000
[1] => 1621880102606
[2] => LOS ANGELES AZULES FT PEPE AGILAR
[3] => 97008
[4] => NI CONTIGO NI SIN TI
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[mountName] => KDLDFMAAC
[timestamp] => 1621879804
[type] => track
)
[property] => Array
(
[0] => 185000
[1] => 1621879804060
[2] =>
FITO OLIVARES
[3] => 97754
[4] => JUANA LA CUBANA
)
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[mountName] => KDLDFMAAC
[timestamp] => 1621879192
[type] => track
)
[property] => Array
(
[0] => 252000
[1] => 1621879192436
[2] => CHON ARAUZA
[3] => 97076
[4] => UN MONTON DE ESTRELLAS
)
)
)
)
您能否提供在此对象内循环的最佳方法?
谢谢!
解决方案
$xml = simplexml_load_file('https://np.tritondigital.com/public/nowplaying?mountName=KFRQFMAAC&numberToFetch=3&eventType=track&request.preventCache=1621376522745');
$tracks = [];
foreach($xml->{'nowplaying-info'} as $item)
{
$properties = [];
foreach ($item->property as $prop) $properties[] = (String) $prop;
$tracks[]=$properties;
}
print_r($tracks);
在这里预览:https ://www.tehplayground.com/8zX2DrFsjVjT1IUK
// output:
Array
(
[0] => Array
(
[0] => 03:07
[1] => 1622057699278
[2] => LIVE AND LET DIE
[3] => 18281
[4] => PAUL MCCARTNEY & WINGS
)
[1] => Array
(
[0] => 04:20
[1] => 1622057449584
[2] => DREAMS
[3] => 18269
[4] => FLEETWOOD MAC
)
[2] => Array
(
[0] => 05:03
[1] => 1622057144393
.....
推荐阅读
- sql - 导入 csv excel 文件时,Laravel 7 时间戳迁移始终返回 0000-00-00 00:00:00
- react-native - React 本机构建过程失败
- tensorflow - rllib - 从检查点获取 TensorFlow 或 PyTorch 模型输出
- python-3.x - Sqlite3 选择查询返回空列表\无值
- python - 有没有办法使 datetime.datetime.now() 输出的时间成为 Windows 的有效参数?
- visual-studio-code - 硬件加速
- python - BS4 获取 python 中元素的完整 CSS 选择器
- ansible - Ansible:在配置文件中修改/添加多行的规范方法
- java - 是否可以将我的 64 位 JavaFX 应用程序移植到 32 位?
- image - 如何创建图像文件,其中图像的某些部分不会导致打印图像的打印机在该位置打印任何内容