在庫状況表示 | もしもAPIをphpで使ってみる

在庫状況表示

もしもAPIに商品オプション情報というのが増えていたので、商品IDを渡すと在庫状況を返す関数をちょこっとつくってみた。

商品オプション情報APIでは、今までの商品情報APIとは異なり、商品が終売になると、APIで、404のステータスコードが返ってくるんですね。その辺をチェックするようにしてみました。
Shift_JISのページにある場合です。

function zaiko($pid) {
$authorization_code = "もしもAPI認証コード";
$search_url = "http://api.moshimo.com/article/option";
$request = $search_url . "?authorization_code=$authorization_code&article_id=$pid";

if(false === $response = @file_get_contents($request) ){
preg_match('|\\AHTTP/\\d\\.\\d +(?\\d{3}) +(?.*)\\E|',
$http_response_header[0], $captures);
if($captures['status_code'] == 404) { //not foundは、終売
return "完売しました";
}
return "";
}

$ArticleOption = simplexml_load_string($response);
if($ArticleOption->Result->Status == "OK"){
$zaiko = "在庫状況:".mb_convert_encoding($ArticleOption->StockStatusWord,
"Shift_JIS", "UTF-8");
return $zaiko;
}
return "";
}


利用する方は、商品IDを以下のように渡せば、最新の在庫状況を返します。
<?php echo zaiko(125188); ?>