はじめに
Twitterのbotを作っている際に、XMLからランダムにつぶやくデータを持ってこようとしたときに、躓いた点があったので書き留めておきます。なお、記事を書くにあたって調べていると、この部分が原因ではなかったのかなという気もしてきましたが。。。笑
Contents
XMLからデータをそのまま取得
簡単な例のために、次のようなXML文字列を用意し、example.phpとします。
<?php $xmlstr = <<<XML <?xml version='1.0' standalone='yes'?> <movies> <movie> <title>PHP: Behind the Parser</title> <characters> <character> <name>Ms. Coder</name> <actor>Onlivia Actora</actor> </character> <character> <name>Mr. Coder</name> <actor>El ActÓr</actor> </character> </characters> <plot> So, this language. It's like, a programming language. Or is it a scripting language? All is revealed in this thrilling horror spoof of a documentary. </plot> <great-lines> <line>PHP solves all my web problems</line> </great-lines> <rating type="thumbs">7</rating> <rating type="stars">5</rating> </movie> </movies> XML; ?>
このファイルから<plot>を取得してみましょう。次のように書きます。
<?php include 'example.php'; $movies = new SimpleXMLElement($xmlstr); echo $movies->movie[0]->plot; ?>
結果は以下の通りです。
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
XML;
$movies = new SimpleXMLElement($xmlstr);
echo $movies->movie[0]->plot;
?>
では、今度はvar_dumpして先程のplotを見てみましょう
var_dump($movies->movie[0]->plot);
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
XML;
$movies = new SimpleXMLElement($xmlstr);
var_dump($movies->movie[0]->plot);
?>
object(SimpleXMLElement)とありますね。これがオブジェクトであると示している?
ということで、これをstringにしたいと思います。
取得したデータをstringにする
具体的には、要素の前に(string)をつけるという処理をします。
そこで、先程のコードに少し加えまして下のようにします。
<?php include 'example.php'; $movies = new SimpleXMLElement($xmlstr); var_dump((string) $movies->movie[0]->plot); ?>
movie[0]->plot);
?>
これでstringになりましたね!この処理を「キャスト」というそうで、
stringを引数する関数に渡すときはこのようにキャストしないといけないようです。
コメントを残す
コメントを投稿するにはログインしてください。