我有这个xml文件(见下文),我想用php解析输出Filename和RomUrl
<?xml version="1.0" encoding="UTF-8"?>
<OTA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ota.xsd">
<Stable>
<cheeseburger>
<Filename>crDroidAndroid-8.1-20180128-cheeseburger-v4.0-BETA5</Filename>
<RomUrl
id="rom"
title="Downloads"
description="Download latest builds">dl url here for cheeseburger</RomUrl>
</cheeseburger>
<dumpling>
<Filename>crDroidAndroid-8.1-20180127-dumpling-v4.0-BETA</Filename>
<RomUrl
id="rom"
title="Downloads"
description="Download latest build">dl url here for dumpling</RomUrl>
</dumpling>
</Stable>
</OTA>
我希望能够像这样输出:
cheeseburger
crDroidAndroid-8.1-20180128-cheeseburger-v4.0-BETA5
dl url here for cheeseburger
dumpling
crDroidAndroid-8.1-20180127-dumpling-v4.0-BETA
dl url here for dumpling
现在我被困在循环每个元素 这是我到目前为止的代码
<?php
// Devices.xml reader
// check if file exists and read it
if (file_exists('devices.xml')) {
$xml = simplexml_load_file('devices.xml');
//echo $xml->Stable->dumpling->Filename;
echo "<br>";
foreach($xml->Stable as $device) {
echo '<h2>' . $device->Filename . '</h2>';
}
echo "<br>";
echo "<br>";
//var_dump($xml);
} else {
exit('Failed to open devices.xml.');
}
?>
现在我确信可能有更好的选择,但我不熟悉php中的XML,所以任何帮助都非常感谢
谢谢
答案 0 :(得分:0)
$device
的类型为SimpleXMLElement,您可以使用foreach
进行循环。
然后,您可以访问$key
以获取“cheeseburger”和$item
(也是SimpleXMLElement类型)以获取“Filename”等属性。
if (file_exists('devices.xml')) {
$xml = simplexml_load_file('devices.xml');
foreach($xml->Stable as $device) {
foreach ($device as $key => $item) {
echo $key . "<br>";
echo $item->Filename . "<br>";
echo $item->RomUrl . "<br>";
echo "<br>";
}
}
} else {
exit('Failed to open devices.xml.');
}
这将导致:
cheeseburger
crDroidAndroid-8.1-20180128-cheeseburger-v4.0-BETA5
dl url here for cheeseburger
dumpling
crDroidAndroid-8.1-20180127-dumpling-v4.0-BETA
dl url here for dumpling