If you want to push the generic with PHP and you want to access PHP variables without knowing their names, know that it can fairly easily without using eval() function or other code unreadable.
Indeed, the flexibility of PHP allows you to "generate" variable names using the characters {}, a small example, suppose a class representing a model (here a news), deliberately simplified.
<?php
class News
{
private $news_title;
private $news_description;
public function __construct($_news_title,$news_description)
{
$this->news_title = $_news_title;
$this->news_description = $news_description;
}
public function __get($name)
{
return $this->{$name};
}
}
?>
Thanks to generic getter __get (), we can access class variables without knowing their name. Imagine, in another file a variable contains the string describing the class variable, we can recover the value from an abstract way like this :
<?php
include("News.class.php");
$news = new News("title","content");
$generic = "news_title";
var_dump($news->__get($generic));
// Display "String(7) content";
?>
If you are a beginner in XSL, beyond the basic features (select, for-each, choose, if variable), you have been surprised not to find a simple for loop, while the for-each was present, but the for-each does not always do everything. So if you want to make a small loop for several solutions available to you. To illustrate, we will take a simple example: a mark/5 on article (float) on the fact that you have this mark this in your XML feed, and you want to display the number of stars corresponding to this mark.
1st solution you are using PHP5 and using the registerPHPFunctions() of class XSLTProcessor(), you can simply use one of your PHP functions to carry out the treatment.
<?php
$xml = new DOMDocument()
$xml->load('flux.xml');
$xsl = new DOMDocument()
$xsl->load('flux.xsl');
$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsl);
echo $proc->transformToXML($xml);
function displayStars($note)
{
$html = "";
for($i=0 ; $i<floor($note) ; $i++)
$html .= '<img src="Public/Styles/Img/star.gif" title="'.floor($note).'/5" />';
echo $html;
}
?>
Thus, in XSL, simply call your PHP function with php xmlns without forgetting the attribute disable-output-escaping to interpret HTML returned your function.
<!--
- Test with XSLTProcessor
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" version="1.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes" />
<xsl:template match="root">
<html>
<head></head>
<body>
<xsl:value-of select="php:function('displayStars',//article/note)" disable-output-escaping="yes" />
</body>
</html>
</xsl:template>
</xsl:stylesheet>
The 2nd solution is based solely on XSL and involves the use of recursive templates to simulate a for loop.
<!--
- Recursive template
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl"" version="1.0">
<xsl:template name="displayStars">
<xsl:param name="i" />
<xsl:param name="length" />
<!-- For Treatment -->
<img src="Public/Styles/Img/star.gif" alt="{concat($length,'/5')}" title="{concat($length,'/5')}" />
<!-- /For Treatment -->
<!-- While length is not reached, we recalled the template to continue the loop -->
<xsl:if test="$i < $length">
<xsl:call-template name="displayStars">
<xsl:with-param name="i" select="$i + 1" />
<xsl:with-param name="length" select="$length" />
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Whether we call it like this:
<!-- - Call recursive template --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" version="1.0"> <xsl:output method="xml" encoding="UTF-8" indent="yes" /> <xsl:template match="root"> <html> <head></head> <body> <xsl:call-template name="displayStars"> <xsl:with-param name="i" select="'1'" /> <xsl:with-param name="length" select="round(//article/note)" /> </xsl:call-template> </body> </html> </xsl:template> </xsl:stylesheet>
Note that even if the for loop in XSL is exploitable, it quickly becomes tedious redevelopment of templates specific to each processing loop.
A 3rd solution, for large projects, if we keep the same example of the mark, is to arrange to slightly modify the structure of its formed XML as PHP to achieve its treatment with only the for-each.
Here, instead of training:
<?xml version="1.0" encoding="UTF-8"?> <root> <article> <note><![CDATA[3.4]]></note> </article> </root>
It might have been formed:
<?xml version="1.0" encoding="UTF-8"?> <root> <article> <note> <item><![CDATA[]]></item> <item><![CDATA[]]></item> <item><![CDATA[]]></item> </note> </article> </root>
where the number of item corresponding at floor() php in order to "foreach" quietly on our marks and simulate a for loop:
<!--
- Fake for-each
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" version="1.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes" />
<xsl:template match="root">
<html>
<head></head>
<body>
<xsl:variable name="note" select="count(//article/note/item)" />
<xsl:for-each select="//article/note/item">
<img src="Public/Styles/Img/star.gif" alt="{concat($note,'/5')}" title="{concat($note,'/5')}" />
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
You can see several solutions that allow you to make your loop, you are free to choose what suits you best, with your technical envirronnement and your choice of architecture.
If you are interested in MySQL (or PHP) recover comments tables and / or comments from the columns of a table, remember that it is very easy to access this information directly from a query.
Retrieving comments for a table :
# 'sillysmart' is the name of the database you want to extract information mysql> SHOW TABLE STATUS FROM sillysmart mysql>
will produce the following informations:
| Name | Engine | Version | Rows | Comment |
|---|---|---|---|---|
| Country | MyISAM | 10 | 240 | Countries Listing |
| News | MyISAM | 10 | 30 | News Listing |
Where the column 'Comment' will give you the information, the commentary of the table. Know that many other informations are available through this application.
Retrieve the comments columns of a table :
# 'Country' is the table name you want mysql> SHOW FULL COLUMNS FROM Country mysql>
will produce the following informations:
| Field | Type | Collation | Null | Key | Extra | Privileges | Comment |
|---|---|---|---|---|---|---|---|
| country_id | bigint(20) | NULL | NO | PRI | auto_increment | select,insert,update | Id |
| country_name | varchar(255) | latin1_swedish_ci | NO | UNI | select,insert,update | Country Name | |
| country_tld | varchar(2) | latin1_swedish_ci | YES | select,insert,update | Country TLD |
Where the column 'Comment' will give you the information, the comment column of the table.
Free for you to use this information in PHP. Personally we use these columns in a transparent way on SillySmart to create generic back-office remains speaking for a non-scientist. The only constraint is that the length of the commentary is limited to 60 characters, so be succinct!
A major new features of PHP5 is that the parsing of XML / XSL XSLTProcessor will natively use PHP to perform heavy and cumbersome transformations before. Now, no need to do to make a template to do ucwords(), just a little setup and we are good.
At PHP's level :
<?php
$xml = new DOMDocument();
$xml->load('flux.xml');
$xsl = new DOMDocument();
$xsl->load('flux.xsl');
$proc = new XSLTProcessor();
// It specifies the parser that it wants to use PHP functions in XSL
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsl);
echo $proc->transformToXML($xml);
?>
At XSL's level :
<!--
- Simple test to call php function
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl"
version="1.0">
<!-- We add the PHP's xmlns -->
<xsl:output method="xml" encoding="UTF-8" indent="yes" />
<xsl:template match="root">
<html>
<!-- We use the php suffix to call the function ucwords() -->
<xsl:value-of select="php:function('ucwords','php can now be used in xsl')" />
<!-- Output: 'Php Can Now Be Used In Xsl' -->
</html>
</xsl:template>
</xsl:stylesheet>
You can even use static functions of class, at PHP's level :
<?php
class XSL
{
/**
* stringToUrl
*
* @param $string the string
* @param $delimiter the implode character
* @return $string the string modified
* @see self::fullTrim
* @see self::removeSpecialCaracteres
* @see self::removeAccents
*/
static function stringToUrl($string,$delimiter=" ")
{
return self::fullTrim(self::removeSpecialCaracteres(strtolower(self::removeAccents($string))),
$delimiter);
}
/**
* Remove accents in string
*
* @param $string the string
* @return $string the string modified
*/
static function removeAccents($string)
{
static $search = array ("à", "á", "â", "ã", "ä", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï",
"ñ", "ò" ,"ó", "ô", "õ", "ö", "ù", "ú", "û", "ü", "ý", "ÿ", "À", "Á",
"Â", "Ã", "Ä", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ñ", "Ò",
"Ó", "Ô", "Õ", "Ö", "Ù", "Ú", "Û", "Ü", "Ý");
static $replac = array ("a", "a", "a", "a", "a", "c", "e", "e", "e", "e", "i", "i", "i", "i",
"n", "o", "o", "o", "o", "o", "u", "u", "u", "u", "y", "y", "A", "A",
"A", "A", "A", "C", "E", "E", "E", "E", "I", "I", "I", "I", "N", "O",
"O", "O", "O", "O", "U", "U", "U", "U", "Y");
return str_replace($search,$replac,$string);
}
/**
* Remove special chars in string
*
* @param $string the string
* @return $string the string modified
*/
static function removeSpecialCaracteres($string)
{
static $search = array ("²", "&", "~", "#", "{", "(", "[", "-", "|", "`", "\\", "^", "'", ")",
"]", "}", "^", "¨", "£", "¤", "%", "*", ",", "?", ";", ".", ":",
"/", "!", "§", "<", ">", "»", "«", "\n", "\r", " ");
static $replac = " ";
return str_replace($search,$replac,$string);
}
/**
* Perform a full trim in string
*
* @param string $element the string
* @param $delimiter implode glue
* @return string the string modified
*/
static function fullTrim($element,$delimiter="")
{
return implode($delimiter,self::processFunction(explode(' ',$element),'trim'));
}
}
?>
And at XSL's level :
<!--
- More complex test to call php class function
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl"
version="1.0">
<xsl:output method="html" version="XHTML 1.0" encoding="UTF-8" indent="yes" />
<xsl:template match="root">
<html>
<!-- We use the php suffix to call the static class function stringToUrl() -->
<xsl:value-of select="php:function('XSL::stringToUrl','une_superstring-àÔ|modifier')" />
<!-- Output: 'une_superstring ao modifier' -->
</html>
</xsl:template>
</xsl:stylesheet>
We can therefore easily implement PHP's changes to our XSL templates.