IKEA stock notifications using PHP and XML

Recently, my girlfriend and I visited IKEA to look for a new bedroom dresser.   We found one we liked but were informed that it was out of stock.  

IKEA stock check tool

IKEA stock check tool

Website

IKEA has a stock check form on its product pages.   However, there is no way to sign-up for notifications when a product is in stock so you'll need to keep checking back periodically.  

API

After inspecting the page, I discovered that the API URL for checking the stock is:

http://www.ikea.com/us/en/iows/catalog/availability/{productNumber}

Issuing a GET request with a valid product number will return XML data containing the stock status at every IKEA location in the United States.    The location code is named buCode.

How do we find the location code for our store?  We can look at the value attribute in the dropdown option tag from the HTML form: 

<option value="153">PA, Pittsburgh</option>

Below is an excerpt from the XML response:

<localStore buCode="153" timeZoneOffsetInMillis="-14400000">
    <stock>
        <partNumber>20245370</partNumber>
        <isMultiProduct>false</isMultiProduct>
        <isSoldInStore>true</isSoldInStore>
        <isInStoreRange>true</isInStoreRange>
        <restockDate>2016-05-14</restockDate>
        <isValidForNotification>true</isValidForNotification>
        <availableStock>0</availableStock>
        <inStockProbabilityCode>LOW</inStockProbabilityCode>
        <validDate>2016-05-09</validDate>
        ...
    </stock>
</localStore>

Automated Notifications

Now we're ready to write an automated program to check the stock.   Here I'm using my own messaging class called SMS to generate a text message to my phone.   You can obviously replace with your own code as needed.

$url = 'http://www.ikea.com/us/en/iows/catalog/availability/20245370';

try
{
    $xml = new SimpleXMLElement(file_get_contents($url));

    foreach ($xml->availability[0]->localStore as $store)
    {
        if ($store['buCode'] == 153)
        {
            $stock = $store->stock->availableStock;
       
            if ($stock > 0)
            {
                $sms = new SMS;
                $sms->send('555-555-0000',"IKEA product in stock - $stock");
            }
            break;
        }
    }
}
catch (Exception $e)
{
    echo 'Caught exception: ' . $e->getMessage() . "\n";
}