我想将从Kunaki API收到的xml解析为下拉选择框。到目前为止我有这个代码,但是盒子保持空白,所以我的问题是我如何实现这个目标?我每次都会收到一个空的下拉选择框。
<?php
$context = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$url = 'http://kunaki.com/HTTPService.ASP?RequestType=ShippingOptions&State_Province=NY&PostalCode=11204&Country=United+States&ProductId=PX0012345&Quantity=1&ProductId=PX04444444&Quantity=1&ResponseType=xml ';
$xml = file_get_contents($url, false, $context);
$xml2 = simplexml_load_string($xml);
?>
<html>
<head>
</head>
<body>
<select>
<Option Value=<?php echo $value = (string)$xml2->Description[0]." Delivery Time ".(string)$xml2pt->DeliveryTime[0].(string)$xml2->Price[0];?></Option>
</select>
</body>
</html>
答案 0 :(得分:0)
经过一番摆弄后,我相信这就是你所追求的目标。
<?php
// Setup your context for file_get_contents
$oContext = stream_context_create(array("http" => array("header" => "Accept: application/xml")));
// Put in your URL here to get the XML from
$sURL = "http://kunaki.com/HTTPService.ASP?RequestType=ShippingOptions&State_Province=NY&PostalCode=11204&Country=United+States&ProductId=PX0012345&Quantity=1&ProductId=PX04444444&Quantity=1&ResponseType=xml";
// Parse the XML
$oXML = simplexml_load_string(file_get_contents($sURL, false, $oContext));
// Grab the data that we need from the XML
$pOptions = isset($oXML->Option) && isset($oXML->Option[0]) ? $oXML->Option : array("error" => true);
// Display everything to the page
echo "<html>";
echo "<head>";
echo "<title>XML Test</title>";
echo "</head>";
echo "<body>";
// If there was an error, display it to the page
if(isset($pOptions["error"]))
{
echo "<h3>Sorry, wrong data returned.";
var_dump($pOptions);
}
else
{
// Loop through the array and display the dropdown
echo "<select>";
for($i = 0, $iCount = count($pOptions); $i < $iCount; ++$i)
{
$sString = $pOptions[$i]->Description.", ";
$sString .= "Delivery Time: ".$pOptions[$i]->DeliveryTime." ";
$sString .= "($".$pOptions[$i]->Price.")";
echo "<option>".$sString."</option>";
}
echo "</select>";
}
echo "</body>";
echo "</html>";
?>
我重新格式化了下拉文本的显示,以便更容易阅读。 在这个例子中,它使这个下拉列表:
<select>
<option>
USPS First Class Mail, Delivery Time: 2-5 business days ($0.66)
</option>
<option>
UPS Ground, Delivery Time: 1-5 business days ($17.17)
</option>
<option>
UPS 2nd Day Air, Delivery Time: 2 business days ($30.42)
</option>
<option>
UPS Next Day Air Saver, Delivery Time: 1 business day ($50.17)
</option>
</select>
您的一个问题是,您只将数据放入下拉列表的值属性中。
示例:
<option value="test"></option>
只会显示:
<select>
<option value="test"></option>
</select>
所以你所追求的是更像这样的东西:
<select>
<option>Test</option>
</select>
除此之外,您只是尝试显示第一个返回的选项,而不是所有选项。 这就是for()循环发挥作用的地方,它将循环显示所有返回的运输选项,无论有多少。
希望这有帮助!