用PHP读取XML

时间:2014-03-26 08:48:15

标签: php xml

我正在使用PHP读取XML来测试一些东西。以下是XML文件的示例:

<?xml version="1.0" encoding="UTF-8" ?>
<BroadcastData creationDate="20140326085217">
<ScheduleData>
<ChannelPeriod beginTime="20140326090000" endTime="20140402044500">
<ChannelId>Rai Uno</ChannelId>
<Event beginTime="20140326090000" duration="1800">
<EventId>260852180006</EventId>
<EventType>P</EventType>
<EpgProduction>
<EpgText language="eng">
<Name>Unomattina storie vere</Name>
</EpgText>
</EpgProduction>
</Event>
<Event beginTime="20140326093000" duration="1500">
<EventId>260852180007</EventId>
<EventType>P</EventType>
<EpgProduction>
<EpgText language="eng">
<Name>Unomattina Verde</Name>
</EpgText>
</EpgProduction>
</Event>

这是我构建的PHP脚本,但是当我运行PHP文件时没有显示。

<?php 

$completeurl ="test.xml";
$xml = simplexml_load_file($completeurl);

$info = $xml->BroadcastData->ScheduleData->ChannelPeriod->ChannelId;

for ($i = 0; $i++) {
$begintime = $info[$i]->Event->attributes()->beginTime;


echo "<p>Channel: ".$info."<br/>"."Begin Time: ".$begintime."</p>";
}



?>

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

你应该迭代每个通道周期而不是通道id(无论如何都是子元素):

$doc = simplexml_load_file($completeurl);

foreach ($doc->ScheduleData->ChannelPeriod as $channelPeriod) {
    $channelId = (string)$channelPeriod->ChannelId;

    foreach ($channelPeriod->Event as $event) {
        $beginTime = $event['beginTime'];

        printf('<p>Channel: %s<br />Begin Time: %s</p>', $channelId, $beginTime);
    }
}

答案 1 :(得分:0)

使用以下函数将xml字符串转换为数组

  json_decode(json_encode((array)simplexml_load_string($sXML)),1);