1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでXML形式のAPIレスポンスを受け取る際の注意事項

Posted at

XML形式でレスポンスを返却するAPIに対して、PHP側で連想配列への変換を行う際には、通常

// curlの実行
$url = 'http://www.xxxxxxxxxx.yy.zz/getFruits/';
$curl = curl_init($url);
$xml = curl_exec($curl);

// 受け取ったXMLレスポンスをPHPの連想配列へ変換
$xmlObj = simplexml_load_string($xml);
$json = json_encode($xmlObj);
$response = json_decode($json, true);

このようなフローを踏むことになるが、上記処理を行うとXMLの特性である同名要素を複数持てるという性質に対応した際に問題が発生する。

パターン1:

<?xml version="1.0" encoding="utf-8"?>
<data>
    <fruits>
        <name>apple</name>
        <price>100</price>
    </fruits>
</data>

// PHP変換後
$response = array('fruits' => array('name' => 'apple',
                                    'price' => '100'
                              )
            );

パターン2:

<?xml version="1.0" encoding="utf-8"?>
<data>
    <fruits>
        <name>apple</name>
        <price>100</price>
    </fruits>
    <fruits>
        <name>orange</name>
        <price>80</price>
    </fruits>
</data>

// PHP変換
$response = array('0' => array('fruits' => array('name' => 'apple',
                                                 'price' => '100'
                                           )
                         ),
                  '1' => array('fruits' => array('name' => 'orange',
                                                 'price' => '80'
                                           )
                         )
            );

パターン1のように、同名要素が存在しない場合は、連想配列に変換されるが
パターン2のように、同名要素が複数存在する場合は、配列が作られた上でその配下に格納されてしまい、参照の仕方が変わってきてしまう。

したがって自分は以下のような対応を行い、データが1種類しか返却されないパターンでも必ず配列になるように対応をした


function addNumberToArray($arr)
{
    // 連想配列の時は配列へ変更
    if (!empty($arr) && array_values($arr) !== $arr) {
        $arr = array($arr);
    }

    return $arr;
}

$fruits = addNumberToArray($response['fruits']);

foreach ($fruits as $fruit) {
    echo $fruit['name'] . 'は' . $fruit['price'] . '円です';
}

こうすることで同名要素が一つの場合でも複数の場合でも同様の対応を行うことができた

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?