Иазяв Posted November 24, 2012 Report Share Posted November 24, 2012 Подскажите, пожалуйста. У меня есть БД. Из нее данные достаются php-файлом и формируется xml, который потом "скрещивается" с xsl и выдается ответ. Вопрос в том, что у меня разные xsl-фрагменты (для каждого определенного запроса свой). Знаю, что эти фрагменты могут содержатся в одном xsl-файле. Как достать нужный фрагмент? Городить кучу xsl-файлов не хочу. Глупо. А как из одного достать нужный среди множества других, не знаю. Link to comment Share on other sites More sharing options...
Иазяв Posted November 27, 2012 Author Report Share Posted November 27, 2012 Если вдруг кому-то понадобиться... Решила это так, хотя можно и чуточку оптимизировать в некоторых местах. php- файл, отвечающий за обработку вызова: <?phpclass THandler{private $xmlDoc;public function __construct(){ $this->xmlDoc = new DOMDocument();}//------------------------------------------------------------------------------------------public function Execute ($Event){ switch ( $Event ) { case "BANNER": $this->Banner(); break; case "MODULES": $this->Modules(); break; case "NEWS": $this->News(); break; case "ACTIONS": $this->Actions(); break; case "FOOTER": $this->Footer(); break; case "FRAME": $this->Frame(); break; } //ф-ия создаст хмл-док, потом объединит с хсл-ем $xsl = new DOMDocument(); $xsl->load("hm3.xsl"); // Configure the transformer $proc = new XSLTProcessor(); $proc->importStyleSheet($xsl); // attach the xsl rules /*//так лучше, изза "transformToXML () принимает атрибут во внимание" в строчках stylesheet $newXml = $proc->transformToXML($xml); echo $newXml; */ return trim($proc->transformToDoc($this->xmlDoc)->saveXML());}//============================================================================================private function Frame (){ $Root = $this->xmlDoc->createElement("root"); $this->xmlDoc->appendChild($Root); $Root->appendChild($this->xmlDoc->createElement("event", "FRAME"));}//--------------------------------------------------------------------------------------------private function Banner (){ $Root = $this->xmlDoc->createElement("root"); $this->xmlDoc->appendChild($Root); $Root->appendChild($this->xmlDoc->createElement("event", "BANNER"));}//--------------------------------------------------------------------------------------------private function Footer (){ $Root = $this->xmlDoc->createElement("root"); $this->xmlDoc->appendChild($Root); $Root->appendChild($this->xmlDoc->createElement("event", "FOOTER"));}//--------------------------------------------------------------------------------------------private function Modules (){ $Modules = $this->Select ("modules"); if ( is_array($Modules) ) { $Root = $this->xmlDoc->createElement("root"); $this->xmlDoc->appendChild($Root); $Root->appendChild($this->xmlDoc->createElement("event", "MODULES")); foreach ( $Modules as $Module ) {$Mod = $this->xmlDoc->createElement("module");$Root->appendChild($Mod);$Mod->appendChild($this->xmlDoc->createElement("title", $Module['title'])); } } else $this->Errors ("Database is unvailabe. Try again later.");}//----------------------------------------------------------------------------------------------------private function News (){ $News = $this->Select ("news"); if ( is_array($News) ) { $Root = $this->xmlDoc->createElement("root"); $this->xmlDoc->appendChild($Root); $Root->appendChild($this->xmlDoc->createElement("event", "NEWS")); foreach ( $News as $New ) {$Now = $this->xmlDoc->createElement("new");$Root->appendChild($Now);$Now->appendChild($this->xmlDoc->createElement("title", $New['title'])); $Now->appendChild($this->xmlDoc->createElement("ndate", $New['ndate'])); $Now->appendChild($this->xmlDoc->createElement("comment", $New['comment'])); } } else $this->Errors ("Database is unvailabe. Try again later.");}//-----------------------------------------------------------------------------------------------private function Actions (){ $Actions = $this->Select ("actions"); if ( is_array($Actions) ) { $Root = $this->xmlDoc->createElement("root"); $this->xmlDoc->appendChild($Root); $Root->appendChild($this->xmlDoc->createElement("event", "ACTIONS")); foreach ( $Actions as $Action ) {$Act = $this->xmlDoc->createElement("act");$Root->appendChild($Act);$Act->appendChild($this->xmlDoc->createElement("begin_date", $Action['bdate'])); $Act->appendChild($this->xmlDoc->createElement("end_date", $Action['edate'])); $Act->appendChild($this->xmlDoc->createElement("essential", $Action['title'])); $Act->appendChild($this->xmlDoc->createElement("about", $Action['comment'])); } } else $this->Errors ("Database is unvailabe. Try again later.");}//--------------------------------------------------------------------------------------------------private function Select ($TableName){ $LinkSQL = mysql_connect('здесь ваши параметры'); $Data = false; if ( is_resource($LinkSQL) ) { $ResultLink = mysql_query("select * from tech." . $TableName, $LinkSQL); if ( is_resource($ResultLink) ) {$Data = array();// $Count = mysql_num_fields($ResultLink);while ( $Row = mysql_fetch_assoc($ResultLink) ){ foreach ( $Row as $Key => $Value ) $Row[$Key] = iconv("WINDOWS-1251", "UTF-8", $Value); $Data[] = $Row;} } mysql_close($LinkSQL); } return $Data;}//-----------------------------------------------------------------------------------------------------private function Errors ($Text){ $Root = $this->xmlDoc->createElement("root"); $this->xmlDoc->appendChild($Root); $Root->appendChild($this->xmlDoc->createElement("event", "ERRORS")); $Root->appendChild($this->xmlDoc->createElement("text", $Text));}}?> ajax, делающий запрос и получающий ответ function DoRequest(post, id){ var httpRequest = null; try { httpRequest = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) {try{ httpRequest = new ActiveXObject('Microsoft.XMLHTTP');}catch (E){ httpRequest = false;} } if ( !httpRequest && typeof XMLHttpRequest != 'undefined' ) { httpRequest = new XMLHttpRequest(); } httpRequest.open('POST', 'hm3.php', false); httpRequest.send(post); if ( httpRequest.status == 200 ) { // если статус 200 (ОК) - выдать ответ пользователю document.getElementById(id).innerHTML = httpRequest.responseText; }}function InitFrame(){ DoRequest('BANNER', 'banner');//параметры - что(свич пхп работает на этом) и куда:DoRequest('MODULES', 'left');DoRequest('NEWS', 'news');DoRequest('ACTIONS', 'right');DoRequest('FOOTER', 'footer');} и собственно xsl-файл, показывающий что и как выводить <?xml version="1.0" encoding="WINDOWS-1251"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/"> <xsl:choose> <xsl:when test="root/event = 'FRAME'"><html><head> <meta http-equiv="Content-Type" content="text/html; charset=WINDOWS-1251" /> <title>Test page</title> <link rel="stylesheet" type="text/css" href="hm3.css" /> <script type="text/javascript" src="hm3.js"><xsl:comment /></script></head><body onload="javascript:InitFrame();"> <div class="container"> <div class="banner" id="banner">-</div> <div class="left" id="left">-</div> <div class="news" id="news">-</div> <div class="right" id="right">-</div> <div class="footer" id="footer">-</div> </div></body></html> </xsl:when> <xsl:when test="root/event = 'ACTIONS'"><xsl:for-each select="root/act"> <p class="date"><xsl:value-of select="begin_date" />- <xsl:value-of select="end_date" /> </p> <p class="title"><xsl:value-of select="essential" /></p> <p><xsl:value-of select="about" /></p> <hr /></xsl:for-each><!-- <xsl:for-each select="root/act"> <p><xsl:value-of select="begin_date" />- <xsl:value-of select="end_date" /> </p> <p><a> <xsl:attribute name="href">#</xsl:attribute> <xsl:attribute name="title"><xsl:value-of select="about" /></xsl:attribute> <xsl:value-of select="essential" /> </a></p> <br /> <hr /></xsl:for-each> --> </xsl:when> <xsl:when test="root/event = 'ERRORS'"><!-- <p>fsf<xsl:value-of select="root/text" />fcf</p> --><span><xsl:value-of select="root/text"></xsl:value-of></span> </xsl:when> <xsl:when test="root/event = 'NEWS'"><xsl:for-each select="root/new"> <p class="title"><xsl:value-of select="title" /></p> <p class="date"><xsl:value-of select="ndate" /></p> <p><xsl:value-of select="comment" /></p> <hr /></xsl:for-each> </xsl:when> <xsl:when test="root/event = 'MODULES'"><xsl:for-each select="root/module"> <button><xsl:value-of select="title" /></button> <br /> </xsl:for-each> </xsl:when> <xsl:when test="root/event = 'FOOTER'">Footer </xsl:when> <xsl:when test="root/event = 'BANNER'"><span>Banner</span> </xsl:when> </xsl:choose></xsl:template></xsl:stylesheet> Не претендую на самое лучшее решение. Главное, что заработало! :) 1 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now