Skip to content
Advertisement

Show only a specific part of html response in php

I am trying to get tracking information from amazon using provided url 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

I am getting response using file_get_contents() function in php, what I want is to show only that part of the response which contains the tracking information as an output of my php script and eliminate/hide all the unnecessary content from file_get_contents() response.

Advertisement

Answer

One way to do what you’re looking for is use DomDocument to filter out the json data in the source ($file) and then use a recursive function to get the elements you need.

You can set the elements you need using an array, $filter. In this example we’ve taken a sample of some of the available data, i.e. :

$filter = [
'orderId', 'shortStatus', 'promiseMessage',
'lastTransitionPercentComplete', 'lastReachedMilestone', 'shipmentId',
];

The code

<?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;
}

Output:

Array
(
    [orderId] => 203-2171364-3066749
    [shortStatus] => IN_TRANSIT
    [promiseMessage] => Arriving tomorrow by 9 PM
    [lastTransitionPercentComplete] => 92
    [lastReachedMilestone] => SHIPPED
    [shipmentId] => 23796758607302
)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement