XMLファイルを開き、解析して出力

概要


サンプル

XML

<?xml version="1.0" encoding="utf-8"?>
<news xmlns:news="http://slashdot.org/backslash.dtd">
	<story>
		<title>テストタイトル1</title>
		<url>http://example.org/article.php?id=20020430/458566</url>
		<time>2002-04-30 09:04:23</time>
		<author>テストユーザー1</author>
		<teaser>ああああ</teaser>
	</story>
	<story>
		<title>テストタイトル2</title>
		<url>http://example.org/article.php?id=20020430/458566</url>
		<time>2002-04-30 09:04:23</time>
		<author>テストユーザー2</author>
		<teaser>いいいい</teaser>
	</story>
</news>
 
 

php

<?php
	// xmlオブジェクトを取得
	$xml = new DOMDocument;
	// xmlオブジェクトをロード
	$rootNode = $xml->load("sample04_1.xml");
 
	// 展開
	echo "<pre>";
	var_dump($xml);
	echo "</pre>";
 
	// 解析
	echo "<pre>";
	processNode($xml);
	echo "</pre>";
 
	// 再帰解析を行いデータを表示
	function processNode($node){
		// 子ノードを取得
		$children = $node->childNodes;
 
		// 子ノードを繰り返し処理
		foreach($children as $key =>$child){
 
			// ノードチェック
			if($child->nodeType == XML_TEXT_NODE){
				// テキストノードの場合
				echo $child->nodeValue;
 
			}else if($child->nodeType == XML_ELEMENT_NODE){
				// 要素ノードの場合
				echo $child->nodeName . ":";
				processNode($child);
			}
		}
	}
 
?>
 
 



最終更新:2012年08月23日 21:31