【发布时间】:2016-08-05 16:30:45
【问题描述】:
我有一个 XML 文档 (traffic.xml),然后我使用 PHP 使用 foreach 仅提取 2 个特定属性,因为原始 XML 中有大量属性来创建 PHP(drivetimeFetch.php)。
我现在需要做的是,使用drivetimeFetch.php,我需要创建另一个xml 文档(carousel_Traffic.xml),其中的元素和属性由我创建的剥离drivetimeFetch.php 中的大约30 行组成。这是我卡住的地方。我能够编写元素和属性,但是如何将每一行放入自己的元素块中。
这是我的 php 的样子:
<?php
$xml1 = new SimpleXMLElement(file_get_contents('https://wsidata.weather.com/201303/en-us/55828880/traffic.xml'));
foreach ($xml1->drivetimes->drivetime as $drivetime) {
echo"<br>";
echo $drivetime['pathName'].":"." ".$drivetime['driveTimeMinutes']."min \n" ;
}
$xml_txt = '<?xml version="1.0" encoding="UTF-8"?>'."\r\n".'<tickerfeed version="2.4">'."\r\n".
'<playlist type="scrolling_carousel" name="TrafficScroll" target="carousel">'."\r\n" ;
$element = '<element>';
$elementClose = '</element>';
$field1 = '<field name="05">';
$fieldClose = '</field>';
$playlistClose = '</playlist>';
$tickerfeedClose = '</tickerfeed>';
$f = fopen("C:\\Users\\Administrator\\Desktop\\carousel_Traffic.xml", "w");
fwrite ($f, $xml_txt. "\r\n" );
fwrite ($f, $element. "\r\n" );
fwrite ($f, $field1. $drivetime['pathName'].":"." ".$drivetime['driveTimeMinutes']."min " . $fieldClose. "\r\n" );
fwrite ($f, $elementClose. "\r\n" );
fwrite ($f, $playlistClose. "\r\n" );
fwrite ($f, $tickerfeedClose. "\r\n" );
fclose ($f);
?>
我需要的是让 carousel_Traffic.xml 看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<tickerfeed version="2.4">
<playlist type="scrolling_carousel" name="TrafficScroll" target="carousel">
<element>
<field name="05">I-278: Bklyn Battery Tunnel to Brooklyn Bridge: 10min </field>
</element>
</playlist>
</tickerfeed>
对于drivetimeFetch.php 中的每一行,我猜这是一个foreach 操作,但我不知道如何做到这一点,以便每一行的pathName 和driveTimeMinutes 都有自己的元素堵塞。如您所见,我让它只适用于一行。
【问题讨论】: