在php中仅显示html响应的特定部分
我正在尝试使用提供的url从amazon获取跟踪信息 我使用php中的在php中仅显示html响应的特定部分,php,Php,我正在尝试使用提供的url从amazon获取跟踪信息 我使用php中的file\u get\u contents()函数得到响应, 我想要的是只显示响应中包含跟踪信息的部分,作为php脚本的输出,并消除/隐藏file\u get\u contents()response中所有不必要的内容。试试这个 <?php $filename = 'https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE
file\u get\u contents()
函数得到响应,
我想要的是只显示响应中包含跟踪信息的部分,作为php脚本的输出,并消除/隐藏file\u get\u contents()
response中所有不必要的内容。试试这个
<?php
$filename = 'https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE_typ?_encoding=UTF8&from=gp&itemId=&orderId=203-2171364-3066749&packageIndex=0&shipmentId=23796758607302';
$file = file_get_contents($filename);
$html = new DOMDocument();
@$html->loadHTML($file);
foreach($html->getElementsByTagName('span') as $a) {
$property=$a->getAttribute('id');
if (strpos($property , "primaryStatus"))
print_r($property);
}
?>
它应该显示“明天晚上9点到达”状态。一种方法是使用DomDocument过滤源(
$file
)中的json数据,然后使用递归函数获取所需的元素
您可以使用数组,$filter
设置所需的元素。在本例中,我们采集了一些可用数据的样本,即:
$filter = [
'orderId', 'shortStatus', 'promiseMessage',
'lastTransitionPercentComplete', 'lastReachedMilestone', 'shipmentId',
];
代码
<?php
$filename = 'https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE_typ?_encoding=UTF8&from=gp&itemId=&orderId=203-2171364-3066749&packageIndex=0&shipmentId=23796758607302';
$file = file_get_contents($filename);
$trackingData = []; // store for order tracking data
$html = new DOMDocument();
@$html->loadHTML($file);
foreach ($html->getElementsByTagName('script') as $a) {
$data = $a->textContent;
if (stripos($data, 'shortStatus') !== false) {
$trackingData = json_decode($data, true);
break;
}
}
// set the items we need
$filter = [
'orderId', 'shortStatus', 'promiseMessage',
'lastTransitionPercentComplete', 'lastReachedMilestone', 'shipmentId',
];
// invoke recursive function to pick up the data items specified in $filter
$result = getTrackingData($filter, $trackingData);
echo '<pre>';
print_r($result);
echo '</pre>';
function getTrackingData(array $filter, array $data, array &$result = []) {
foreach($data as $key => $value) {
if(is_array($value)) {
getTrackingData($filter, $value, $result);
} else {
foreach($filter as $item) {
if($item === $key) {
$result[$key] = $value;
}
}
}
}
return $result;
}
到目前为止你试过什么?你测试过这个吗?这只是打印
id
。此外,我认为OP需要所有的跟踪信息,而不仅仅是当前状态。谢谢,有没有任何方法可以显示时间线以及订单、今天发货、发货、明天到达?您可以使用getElementsByTagName和getAttribute函数来做到这一点。阅读亚马逊网页的源代码
Array
(
[orderId] => 203-2171364-3066749
[shortStatus] => IN_TRANSIT
[promiseMessage] => Arriving tomorrow by 9 PM
[lastTransitionPercentComplete] => 92
[lastReachedMilestone] => SHIPPED
[shipmentId] => 23796758607302
)