我正在我的网店上安装UPS送货计算器API,它可以正确地获取价格,这太棒了!不过,我找不到任何方法将这些价格转换成有用的格式。我想将它们用作php变量。
对于这个例子,我们将称之为mycartcart.php。
api由一个名为ups.hp.的文件执行
当客户将商品放入购物车并填写邮政编码时,他们会单击提交按钮,然后被引导到一个新的购物车页面,该页面运行ups.php脚本并在页面上显示数据(我稍后将删除该页面,以便它可以在后台运行)。如果这些文件中有任何一个是.xml文件,我可能会学习如何解析xml数据或在php中使用simpleXML命令。。。但他们似乎总是想要一个xml文件的位置,而我没有。有人知道如何将我的一个PHP文件中包含的XML数据用作PHP变量吗?
以下是ups.php中的一些代码:
<?php
$ch = curl_init("https://www.ups.com/ups.app/xml/Rate");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_TIMEOUT, 60);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
echo ''. $result. '';
$data = strstr($result, '<?');
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
} else {
$level[$xml_elem['level']] = $xml_elem['tag'];
}
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[''tag'']] = $xml_elem[''value''];';
eval($php_stmt);
}
}
curl_close($ch);
return $params['RATINGSERVICESELECTIONRESPONSE']['RATEDSHIPMENT']['TOTALCHARGES']['MONETARYVALUE'];
}
?>
当我运行这个.php文件时,页面上的文本输出是什么样子的:
HTTP/1.1 100 Continue HTTP/1.1 200 OK Date: Wed, 25 Jul 2012 20:27:46 GMT
Server: Apache X-Frame-Options: SAMEORIGIN Pragma: no-cache
Content-Length: 1589
X-Powered-By: Servlet/2.5 JSP/2.1
Vary: User-Agent Content-Type: application/xml Bare Bones Rate Request1.00011Success03Additional Handling has automatically been set on Package 1.Your invoice may vary from the displayed reference ratesLBS120.0USD65.56USD8.50USD74.06USD65.56USD8.50USD74.06120.0LBS120.0
我想明白了。这是新代码。。。更短。更简单的方式。
我使用php命令进行explode();和普通数组语法,$newvariable=$existing_array[key#];
谢谢大家的评论!
<?php
$ch = curl_init("https://www.ups.com/ups.app/xml/Rate");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_TIMEOUT, 60);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
$upsout = (explode('USD', $result, 15));
$handling = $upsout[3];
echo "Shipping cost is $";
echo $handling;
curl_close($ch);
}
?>