LoginSignup
0
0

More than 5 years have passed since last update.

XML形式レスポンスをPHPでパースした話

Posted at

PHPでXMLをパースするパターンをまとめた

HTTPレスポンス

response.xml
<?xml version="1.0" encoding="UTF-8" ?>
<response>
 <message>&#12510;&#12473;&#12479;&#12540;</message>
 <rate type="moon">7</rate>
 <rate type="star">5</rate>
</response>

パース準備

参照:http://php.net/manual/ja/simplexmlelement.construct.php

parse.php
$xml = new SimpleXMLElement('response.xml', NULL, TRUE);

messageにアクセス

parse.php
echo $xml->message;

実行結果

&#12510;&#12473;&#12479;&#12540;

数値実体参照&#12510;&#12473;&#12479;&#12540; をUTF-8で文字列変換

parse.php
$str = mb_convert_encoding($xml->message, 'UTF-8', 'HTML-ENTITIES');
echo $str;

実行結果

マスター

typeにアクセス

parse.php
foreach ($movies->rate as $val) {
    echo $val['type'] . "\n";
}

実行結果

moon
star
0
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
0
0