モンスターカレンダー

« 2004年8月 »
12345678910111213141516171819202122232425262728293031

2004年8月16日アーカイブ

php:xmllibを使ってみる(続き)

| コメント(0)

(続き)
5.th,tdに属性追加
ルートノードに追加したのと、結局は同じことをする。
ただちょっとはまったのは、EUCでコードを書いているのに XMLLIBでは内部エンコーディングがUTF‐8なのに気づかず、日本語の取得でうまくいかなかった。。。mb_convert_encodingを使って下さい。

(1)スクリプト

function sub_func(){

$doc = domxml_open_file("xmltest.xml");
$root = $doc->root();

//ルートノードに widthという名称の属性を308という値でセットする
$root->set_attribute("width", "308");
//以下、同様に属性セット
$root->set_attribute("cellspacing", "0");
$root->set_attribute("cellpadding", "0");
$root->set_attribute("border", "1");

//セルのbgcolor設定のための配列
$bgcolor_array = array("あか"=>"red", "きいろ"=>"yellow", "みどり"=>"lightgreen", "むらさき"=>"violet");

$tr_array = $doc->get_elements_by_tagname("tr");
$i = 0;
//trの数だけ処理
while ($i  $tr = $tr_array[$i];
 $th = $tr->first_child(); //th
 $thc = $th->first_child();
 $thc_value = $thc->node_value();
 //取得した値("あか"など)を文字コ‐ド変換する
 $thc_value = mb_convert_encoding($thc_value, "EUC-JP", "UTF-8");
 //配列からbgcolor取得
 $attr = $bgcolor_array[$thc_value] ;
 //thの属性セット
 $th->set_attribute("bgcolor", $attr);
 $th->set_attribute("width", "80");

 $td = $tr->last_child(); //td
 //tdの属性セット
 $td->set_attribute("width", "220");

 $i++;
}

echo "

";
//修正した文書 doc を展開して表示
echo htmlspecialchars($doc->dumpmem());
echo "
";

}

(2ブラウザからの実行結果html) [→見る]

               
あかりんご いちご ピクミン
きいろバナナ レモン ゴールデンキウイ ピクミン
みどりきゅうり きゃべつ キウイ
むらさきナス ピクミン

※「XMLでは空白や改行もノードとみなす。」のですが、読みこむときに
$doc = domxml_open_file("xmltest31.xml",DOMXML_LOAD_DONT_KEEP_BLANKS);

と指定すれば、余分な空白、改行は削除してくれました。他にも
DOMXML_LOAD_PARSING
とか、いろいろ指定できるようです。