XMLとXSLファイルを使用してデータを変換

概要


サンプル

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>
 
 

XSL

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output
	method="html"
	indent="yes"
	encoding="utf-8"
/>
 
<xsl:template match="/news">
	<html>
		<head>
			<title>テストサイトタイトル1</title>
		</head>
		<body>
			<xsl:call-template name="stories"/>
		</body>
	</html>
</xsl:template>
 
<xsl:template name="stories">
	<xsl:for-each select="story">
		<h1><xsl:value-of select="title" /></h1>
		<p>
			<xsl:value-of select="author" />(<xsl:value-of select="time"/>)<br />
			<xsl:value-of select="teaser"/>
			[ <a href="{url}">More</a> ]
		</p>
		<hr />
	</xsl:for-each>
</xsl:template>
 
</xsl:stylesheet>
 
 

PHP

<?php
 
	$processor = new XSLTProcessor;
 
	$xsl = new DOMDocument;
	$xsl->load("sample04_2.xsl");
	$processor->importStyleSheet($xsl);
 
	$xml = new DOMDocument;
	$xml->load("sample04_1.xml");
	$result = $processor->transformToXML($xml);
 
	echo "<pre>{$result}</pre>";
?>
 
 



最終更新:2012年08月23日 20:51