以下のような XML を読み込むとする。
<?xml version="1.0" encoding="UTF-8"?>
<items>
<item>
<company>Apple</company>
<browser>Safari</browser>
</item>
<item>
<company>Google</company>
<browser>Chrome</browser>
</item>
<item>
<company>Mozilla Foundation</company>
<browser>Firefox</browser>
</item>
</items>
<items>
<item>
<company>Apple</company>
<browser>Safari</browser>
</item>
<item>
<company>Google</company>
<browser>Chrome</browser>
</item>
<item>
<company>Mozilla Foundation</company>
<browser>Firefox</browser>
</item>
</items>
XML を読み込んだままでは非常に使いづらい。
Array (
[0] => Array (
[tag] => ITEMS
[type] => open
[level] => 1
[value] =>
)
[1] => Array (
[tag] => ITEM
[type] => open
[level] => 2
[value] =>
)
[2] => Array (
[tag] => COMPANY
[type] => complete
[level] => 3
[value] => Apple
)
[3] => Array (
[tag] => ITEM
[value] =>
[type] => cdata
[level] => 2
)
)
以下長過ぎるので略
[0] => Array (
[tag] => ITEMS
[type] => open
[level] => 1
[value] =>
)
[1] => Array (
[tag] => ITEM
[type] => open
[level] => 2
[value] =>
)
[2] => Array (
[tag] => COMPANY
[type] => complete
[level] => 3
[value] => Apple
)
[3] => Array (
[tag] => ITEM
[value] =>
[type] => cdata
[level] => 2
)
)
以下長過ぎるので略
そこで、以下のようにして配列に突っ込む。
<?php
// XML の読み込み
$fileName = file_get_contents("test.xml");
$XMLObj = xml_parser_create("UTF-8");
xml_parse_into_struct($XMLObj, $fileName, $sourceData);
xml_parser_free($XMLObj);
// XML を配列に格納
$elements = array("COMPANY" => array(), "BROWSER" => array());
createArray("COMPANY");
createArray("BROWSER");
// それぞれの要素毎に配列へ追加
function createArray($tagName) {
global $sourceData;
global $elements;
for ($i = 0; $i < count($sourceData); $i++) {
if ($sourceData[$i]["tag"] == $tagName) {
array_push($elements[$tagName], $sourceData[$i]["value"]);
}
}
}
?>
// XML の読み込み
$fileName = file_get_contents("test.xml");
$XMLObj = xml_parser_create("UTF-8");
xml_parse_into_struct($XMLObj, $fileName, $sourceData);
xml_parser_free($XMLObj);
// XML を配列に格納
$elements = array("COMPANY" => array(), "BROWSER" => array());
createArray("COMPANY");
createArray("BROWSER");
// それぞれの要素毎に配列へ追加
function createArray($tagName) {
global $sourceData;
global $elements;
for ($i = 0; $i < count($sourceData); $i++) {
if ($sourceData[$i]["tag"] == $tagName) {
array_push($elements[$tagName], $sourceData[$i]["value"]);
}
}
}
?>
これを print_r() で表示してやると、こうなってあとは配列を使うだけとなる。
Array (
[0] => Apple
[1] => Google
[2] => Mozilla Foundation
)
Array (
[0] => Safari
[1] => Chrome
[2] => Firefox
)
[0] => Apple
[1] => Google
[2] => Mozilla Foundation
)
Array (
[0] => Safari
[1] => Chrome
[2] => Firefox
)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.