【发布时间】:2019-03-12 17:21:55
【问题描述】:
我正在使用 DOMDocument 和 foreach 循环从 XML 文档中提取数据。对于我所追求的数据点之一,style,我创建了一个具有 style name 和 style ID 的关联数组。然后我将 样式名称 导出到 <select> 下拉列表中。我想弄清楚的是如何根据在下拉列表中选择的 style name 创建具有 style ID 的变量。这是我目前所拥有的:
两个样式名称是5dr Avant Wgn Man 和5dr Avant Wgn Auto。这些被导出到下拉列表。他们各自的风格ID是292015和292016。因此,关联数组看起来像5dr Avant Wgn Man => 292015 和5dr Avant Wgn Auto => 292016。
我想要实现的是当从下拉列表中选择5dr Avant Wgn Man 时,292015 设置为等于$variable。因此,echo $variable; 将显示292015。对于另一种风格,反之亦然。
这是我的 PHP:
<html>
<body>
<?php
$xml = file_get_contents('data.xml');
$dom = new DOMDocument();
$dom->loadXML($xml);
?>
<select>
<option selected="selected">Choose style</option>
<?php
foreach ( $dom->getElementsByTagName('style') as $styletwo ) {
$styleid = $styletwo->getAttribute("name");
$styleData [$styleid]= $styletwo->getAttribute("id");;
}
foreach ($styleData as $k=>$v){
?>
<option><?php echo $k;?> </option>
<?php
}
?>
</select>
</body>
</html>
这是我从中提取的 XML 文档:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<VehicleDescription country="US" language="en" modelYear="2008" bestMakeName="Audi" bestModelName="S4" bestStyleName="5dr Avant Wgn" xmlns="urn:description7b.services.chrome.com">
<responseStatus responseCode="Successful" description="Successful"/>
<style id="292015" modelYear="2008" name="5dr Avant Wgn Man" nameWoTrim="5dr Avant Wgn Man" mfrModelCode="8ED549" fleetOnly="false" modelFleet="false" passDoors="4" altBodyType="Station Wagon" drivetrain="All Wheel Drive">
<division id="4">Audi</division>
<subdivision id="5020">Audi</subdivision>
<model id="17308">S4</model>
<basePrice unknown="false" invoice="46137.0" msrp="49610.0" destination="775.0"/>
<bodyType primary="true" id="7">Station Wagon</bodyType>
<marketClass id="53">Small Wagon</marketClass>
<acode>USB80AUC085A0</acode>
</style>
<style id="292016" modelYear="2008" name="5dr Avant Wgn Auto" nameWoTrim="5dr Avant Wgn Auto" mfrModelCode="8ED54L" fleetOnly="false" modelFleet="false" passDoors="4" altBodyType="Station Wagon" drivetrain="All Wheel Drive">
<division id="4">Audi</division>
<subdivision id="5020">Audi</subdivision>
<model id="17308">S4</model>
<basePrice unknown="false" invoice="47162.0" msrp="50710.0" destination="775.0"/>
<bodyType primary="true" id="7">Station Wagon</bodyType>
<marketClass id="53">Small Wagon</marketClass>
<acode>USB80AUC085A1</acode>
</style>
</VehicleDescription>
</S:Body>
</S:Envelope>
我认为某种if statement 与$k 和$v 可能会起作用,但我无法弄清楚。任何帮助将不胜感激。
【问题讨论】:
标签: php arrays xml foreach domdocument