Home » HTML » HTML_CSS » Manual
Provides a simple interface for validate, handle and generate cascading style sheets.
Summary
Why use HTML_CSS ?
Even if a CSS file is easy to modify (text format), there is no PHP interface that provides such degree of handling style sheet declarations. Create from scratch or parsing single or multi data sources begin really so easy with HTML_CSS.
Features
- parse css string.
- parse css file.
- parse multiple css data sources at once.
- output to inline stylesheet declarations.
- output to document internal stylesheet declarations.
- output to standalone stylesheet declarations.
- output to Array of definitions.
- output to string.
- output to file.
- search for selectors and/or properties using Perl-compatible pattern.
- check validity of CSS data source.
- support of At Rules.
System Requirements
Mandatory resources :
- PHP 4.3.0 or newer.
- PEAR 1.5.4 or newer.
- PEAR::HTML_Common 1.2.4 or newer.
- pcre extension.
Optional resources :
- PHP 5.0.0 or newer.
- PEAR::Services_W3C_CSSValidator 0.1.0 or newer.
- PHPUnit 3.2.0 or newer.
About
FAQ
FAQ – Answers to most Frequently Asked Questions
HTML_CSS FAQ
- What does it cost ?
- Do you offer support ?
- I found a bug, what shall I do ?
- What is CSS ?
- What is PEAR ?
- I want to use HTML_CSS without PEAR. Is it possible ?
- I want to know property value of a selector, but it can not exist
- What does it cost ?
-
You can download and use it for free. But don't delete the copyright notice. You can read terms of the license.
- Do you offer support ?
-
YES if there is no answer in this Guide and if you are ready to share some informations such as : your configuration (platform Win *nix mac, PHP version, PEAR packages installed) and perharps your script.
- I found a bug, what shall I do ?
-
You can report it with the bug tracker at PEAR.
- What is CSS ?
-
CSS (an acronym for Cascading Style Sheets) is a simple mechanism for adding style (e.g. fonts, colors, spacing) to Web documents.
HTML_CSS is a PEAR package that provides methods for handling stylesheet declarations.
Version 1.0.0 does not offers yet methods to validate a style sheet.
- What is PEAR ?
-
PEAR (an acronym for PHP Extension and Application Repository) is a framework and distribution system for reusable PHP components.
Don't forget to read also the PEAR Manual and PEAR FAQ.
- I want to use HTML_CSS without PEAR. Is it possible ?
-
Yes it is. First, you need to download package PEAR::HTML_Common version 1.2 or greater.
Extract content (
Common.phpfile) in same directoryHTML/asCSS.phpfile.Last, you should create your own error handler, or disable it. See chapter Error Handler for details.
- I want to know property value of a selector, but it can not exist
-
With previous release than 1.1.0 it was not possible because
HTML_CSS::getStyle()require at least an existing property, or it will return HTML_CSS_ERROR_NO_ELEMENT_PROPERTY.With new function
HTML_CSS::grepStyle()of version 1.1.0, it's now possible.01: <?php 02: require_once 'HTML/CSS.php'; 03: 04: function myErrorHandler() 05: { 06: return PEAR_ERROR_PRINT; // always print all error messages 07: } 08: 09: $styles = ' 10: h1, h2, h3, h4 { padding: 1em; } 11: .highlight p, .highlight ul { margin-left: .5em; } 12: #main p, #main ul { padding-top: 1em; } 13: '; 14: 15: $prefs = array( 16: 'push_callback' => 'myErrorHandler', 17: ); 18: $attribs = null; 19: 20: $css = new HTML_CSS($attribs, $prefs); 21: $css->parseString($styles); 22: 23: $css->getStyle('.highlight p', 'color'); 24: 25: $styles = $css->grepStyle('/highlight/', '/^color$/'); 26: echo '<pre>'; var_dump($styles); echo '</pre>'; 27: ?>- Lines 4-7, 15-17, 20 :
-
Custom error handler is defined to allow script to continue (print message), when
HTML_CSS::getStyle()will raise error at line 23.
- Lines 9-13, 21 :
-
Stylesheet used is :
h1, h2, h3, h4 { padding: 1em; } .highlight p, .highlight ul { margin-left: .5em; } #main p, #main ul { padding-top: 1em; }
- Lines 23, 25 :
-
While
HTML_CSS::getStyle()will raise error (printed by custom error handler), line 25 will return an empty array with no error raised.Reason :
colorproperty does not exist for.highlight pclass selector.
News
News – What is New in version ?
Version 0.2.x
- Initial PEAR public release occured at end of July 2003.
Version 0.3.x
-
Added the ability to parse CSS from string
with
HTML_CSS::parseString() -
Added the ability to parse CSS from file
with
HTML_CSS::parseFile() -
Added the ability to generate CSS and store it
in a file with
HTML_CSS::toFile() - Introduced error handling system with PEAR_ErrorStack.
- Added unit tests with PHPUnit 1.x for API and bugs.
- Retrieve the settings of individual properties
Version 1.0.x
- Introduced a new error handling system: PEAR_ErrorStack was replaced by a simple way to plug in any error handling system you might want (default used PEAR_Error object)
-
HTML_CSS::apiVersion()returns now a string rather than a float; compatible with php.version_compare(). -
Added the ability to parse multiple data sources
(filename, string) at once with
HTML_CSS::parseData() -
Added the ability to identify if HTML_CSS API output
returns an error with
HTML_CSS::isError() - Introduces package xml 2.0 and drop support of package xml 1.0
- Unified API arguments for all group functions
- Klaus Guenther (first package leader) became inactive.
Version 1.1.x
-
Added ability to search if an element/property
is defined or not with
HTML_CSS::grepStyle()
Version 1.2.x
- License changed from PHP 3.01 to BSD.
- Manual license upgrades from version 2.0 to 3.0 of Creative Commons
Version 1.3.x
- Prevent invalid CSS data source in to be parse
- Add Content-Disposition to the headers in display() Implement request 12195
- Remove pointless NEWS file from distribution, clone of ChangeLog.
Version 1.4.x
- Upgrade requirement to PHP 4.3.0 and PEAR 1.5.4 (to avoid security vulnerability)
- Coding Standard fixes: (errors/warnings) following recommandation by PHP_CodeSniffer
- Unit test suites migrated from PHPUnit 1.x to 3.x
- API 1.4.0 introduces new setter/getter PHP5 facility compatible (magic function __set, __get) for read/write CSS options.
- Error handler allow now to use PEAR_ERROR_CALLBACK (local to HTML_CSS) to customize action when an error/exception is raised. No more need to use global PEAR::setErrorHandling.
Version 1.5.x
- Check validity of CSS data source to be parse using the W3C CSS validator service with help of package PEAR::Services_W3C_CSSValidator (require PHP5)
-
Ability to retrieve all options in effect at once
with
HTML_CSS::getOptions() - Add support of At-Rules Implement request 12194
-
Improve support of At-Rules. See bugs
- 16354 Does not parse multiple simple At-rules properly
- 16355 Simple at rules nested within other at rules are reported as top level at rules
- 16357 Multiple equal complex at rules not parsed correctly
- 16358 Multiple media types on media at rule not parsed correctly
- 16359 Multiple selectors on a single rule inside a complex at rule not properly parsed
- 16360 Multiple selectors inside a complex at rule not properly parsed
Getting started
Overview
Overview – features and usage patterns
In brief
The purpose of this tutorial is to give the new users of HTML_CSS an overview of its features and usage patterns. It describes a small subset of available functionality, but points to the parts of the documentation that give a more in-depth overview.
Selectors are one of the most important aspects of CSS as they are used to "select" elements on an HTML page so that they can be styled. We will try to explain basic concepts, and how to do the same with HTML_CSS.
A complete tutorial about CSS selectors can be find at maxDesign .
Basic concepts
What is a rule or "rule set" ?
A rule or "rule set" is a statement that tells browsers how to render particular elements on an HTML page. A rule set consists of a selector followed by a declaration block.
Rule set structure
Rule structure
Declaration block
The HTML_CSS::setStyle() method is the only one
to handle a declaration block.
For example, to declare a such rule :
p { padding: 5px; }
Here is the php code to create the same sentence with HTML_CSS :
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$css->setStyle('p', 'padding', '5px');
$css->display();
?>
Grouping declarations
You can use more than one declaration within a declaration block. Each declaration must be separated with a semicolon ";".
For example, to declare a such rule :
p { padding: 5px; margin: 1px; }
Or, with whitespace added to aid readability :
p {
padding: 5px;
margin: 1px;
}
Here is the php code to create the same sentence with HTML_CSS :
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$css->setStyle('p', 'padding', '5px');
$css->setStyle('p', 'margin', '1px');
$css->display();
?>
Notice that we use twice HTML_CSS::setStyle()
method call to declare each declaration block for the same selector.
Grouping selectors
When several selectors share the same declarations, they may be grouped together to save writing the same rule more than once. Each selector must be separated by a comma. For example :
h1, h2, h3, h4 { padding: 1em; }
.highlight p, .highlight ul { margin-left: .5em; }
#main p, #main ul { padding-top: 1em; }
To produce such result, we will need help of 3 new methods :
HTML_CSS::setSameStyle(),
HTML_CSS::createGroup() and
HTML_CSS::setGroupStyle().
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
// two selector groups only
$css->setStyle('.highlight p', 'margin-left', '.5em');
$css->setSameStyle('.highlight ul', '.highlight p');
// or even this way
$g2 = $css->createGroup('#main p, #main ul');
$css->setGroupStyle($g2, 'padding-top', '2em');
// more than two selector groups
$g1 = $css->createGroup('h1, h2, h3, h4');
$css->setGroupStyle($g1, 'padding', '1em');
$css->display();
?>
We should take care than grouping two selectors may be write
either with
HTML_CSS::setSameStyle() or with couple
HTML_CSS::createGroup() and
HTML_CSS::setGroupStyle().
When we have to group three or more selectors, there is only one possibility:
couple
HTML_CSS::createGroup() and
HTML_CSS::setGroupStyle().
CSS comments
You can insert comments in CSS to explain your code. Like HTML comments, CSS comments will be ignored by the browser. A CSS comment begins with "/*", and ends with "*/". Comments can appear before or within rule sets as well as across multiple lines.
HTML_CSS 1.0.0 has not yet ability to handle comment such as :
/* Comment here */
p
{
margin: 1em; /* Comment here */
padding: 2em;
/* color: white; */
background-color: blue;
}
/*
multi-line
comment here
*/
The common mistake that people make when writing comments is to expect getting all comments describe with such code below : it's an error.
<?php
$css->setComment('comment here');
$css->setStyle('p', 'margin', '1em');
$css->setStyle('p', 'padding', '2em');
$css->setComment('color: white;');
$css->setStyle('p', 'background-color', 'blue');
$css->setComment('
multi-line
comment here
');
?>
You will only get such result:
/*
multi-line
comment here
*/
p {
margin: 1em;
padding: 2em;
background-color: blue;
}
Only one comment is allowed due to usage of parent class method
HTML_Common::setComment().
Grouping selectors
Grouping selectors – how to handle multiple selector at once
In brief
Remember, when several selectors share the same declarations, they may be grouped together to save writing the same rule more than once. Each selector must be separated by a comma.
Two cases exists to handle group of selector. The quick and limited solution
(accept only two selectors in a same group) with :
HTML_CSS::setSameStyle().
And the extended/common solution with :
HTML_CSS::createGroup(),
HTML_CSS::setGroupStyle(),
HTML_CSS::addGroupSelector() and
HTML_CSS::removeGroupSelector().
Create group
HTML_CSS::createGroup() creates basically
a group for selectors given as first argument. You can identify this group
by an identifier (alphanumeric) or let HTML_CSS manage an internal numeric
identifier itself.
Let creates this group of selectors :
#main p, #main ul { padding-top: 1em; color: red; }
Identify the group yourself
Identifier is named myGroupID in this example:
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$g1 = $css->createGroup('#main p, #main ul', 'myGroupID');
$css->setGroupStyle($g1, 'padding-top', '1em');
$css->setGroupStyle($g1, 'color', 'red');
$css->display();
?>
Let HTML_CSS do it itself
This is the default behavior.
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$g1 = $css->createGroup('#main p, #main ul');
$css->setGroupStyle($g1, 'padding-top', '1em');
$css->setGroupStyle($g1, 'color', 'red');
$css->display();
?>
Handle group selector
With
HTML_CSS::addGroupSelector() and
HTML_CSS::removeGroupSelector(), we have ability to
add or remove one selector from a selectors list (of a group).
Suppose we have these selectors :
html, body { margin: 2px; padding: 0; border: 0; }
and we want to apply same share properties to new class 'large' and do not anymore apply it to 'body'.
Here are how to do :
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
// 1. create the pre-requires data
$g1 = $css->createGroup('html, body');
$css->setGroupStyle($g1, 'margin', '2px');
$css->setGroupStyle($g1, 'padding', '0');
$css->setGroupStyle($g1, 'border', '0');
// 2. remove the body selector
$css->removeGroupSelector(1, 'body');
// 3. add the new 'large' class
$css->addGroupSelector(1, '.large');
$css->display();
?>
Remember that HTML_CSS handle group (numeric) identifier itself (begin at 1, and go to 2, 3, and more).
Parsing data sources
Parsing data sources – load existing style sheet from different data sources
In brief
One of the great features of HTML_CSS is to parse and load existing style sheet
from different data sources : (simple string, css file, combine).
We will see in detail all these possibilities with 3 methods :
HTML_CSS::parseString(),
HTML_CSS::parseFile() and
HTML_CSS::parseData().
Parse a simple string
A quick way to create multiple selector definitions in one step is to use the
HTML_CSS::parseString() function.
Let creates these definitions :
html, body {
margin: 2px;
padding: 0px;
border: 0px;
}
p, body {
margin: 4px;
}
Very easy with such script :
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$strcss = '
html, body {
margin: 2px;
padding: 0px;
border: 0px;
}
p, body {
margin: 4px;
}
';
$css->parseString($strcss);
$css->display();
?>
Parse a file contents
Another quick way to create multiple selector definitions in one step is to use the
HTML_CSS::parseFile() function.
CSS file to load is supposed to be W3C/CSS compliant.
If previous selector definitions was into a file named 'styles.css', then to parse and load contents will be done with such script :
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$css->parseFile('styles.css');
$css->display();
?>
If there are duplicate definitions into file contents, you should parse file with call :
<?php $css->parseFile('styles.css', true); ?>We will see next why we may find such duplicate definitions.
Parse multi data sources
We have already seen two single sources where CSS data could come from.
The last one allow to parse data from multiple sources at once.
HTML_CSS::parseData() function take an array
as first argument. Each item is either a filename (with .css extension) or
a string. Each source is merge to produce at end a unique style sheet.
In script below we load selector definitions from two independent sources: a string and a css file which contents duplicate definitions (parseFile() 2nd argument to set to true to catch this situation; see next section for explains). Internet Explorer).
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
// 1. a string to parse
$strcss = '
body, p { background-color: white; font: 1.2em Arial; }
p, div#black { color: black; }
div{ color: green; }
p { margin-left: 3em; }
';
$css->parseString($strcss);
// 2. a css file with duplicate definitions
$css->parseFile('iehack.css', true);
$css->display();
?>
Allow duplicate definitions
Internet Explorer <= 6 does not handle box model in same way as others browsers that are better W3C compliant. For this reason, we need to fix boxes size with a hack such as this one you can find in example that follow. You can notice the duplicate 'voice-family' and 'height' properties.
To parse these definitions we need to activate the duplicate option of HTML_CSS.
#header {
background-color: ivory;
font-family: "Times New Roman", Times, serif;
font-size: 5mm;
text-align: center;
/* IE 5.5 */
height:81px;
border-top:1px solid #000;
border-right:1px solid #000;
border-left:1px solid #000;
voice-family: "\"}\"";
voice-family: inherit;
/* IE 6 */
height: 99px;
}
There are two ways :
- global to all functions: set option allowduplicates on class constructor
- local to a function: set argument duplicates to TRUE
For example here, we could wrote either (allow global duplicate) :
<?php
require_once 'HTML/CSS.php';
$attr = array('allowduplicates' => true);
$css = new HTML_CSS($attr);
$strcss = '
#header {
background-color: ivory;
font-family: "Times New Roman", Times, serif;
font-size: 5mm;
text-align: center;
/* IE 5.5 */
height:81px;
border-top:1px solid #000;
border-right:1px solid #000;
border-left:1px solid #000;
voice-family: "\"}\"";
voice-family: inherit;
/* IE 6 */
height: 99px;
}
';
$css->parseString($strcss);
$css->display();
?>or also (duplicate on local call) :
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$strcss = '
#header {
background-color: ivory;
font-family: "Times New Roman", Times, serif;
font-size: 5mm;
text-align: center;
/* IE 5.5 */
height:81px;
border-top:1px solid #000;
border-right:1px solid #000;
border-left:1px solid #000;
voice-family: "\"}\"";
voice-family: inherit;
/* IE 6 */
height: 99px;
}
';
$css->parseString($strcss, true);
$css->display();
?>
Output
Output – getting results in different format
In brief
Handle selectors, groups, properties are some basic features of HTML_CSS but
getting results in different format should be the final step of your process.
We have four/five different functions (depending or render you want to get) :
HTML_CSS::toArray(),
HTML_CSS::toInline(),
HTML_CSS::toFile(),
HTML_CSS::toString() and
HTML_CSS::display().
To Array
HTML_CSS::toArray() must be considered
as a debug/help function. An easy way to explore HTML_CSS data structures.
For example, explore these definitions :
html, body {
margin: 2px;
padding: 0px;
border: 0px;
}
p, body {
margin: 4px;
}
div#header { text-align: center; color: red; }
With script :
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$strcss = '
html, body {
margin: 2px;
padding: 0px;
border: 0px;
}
p, body {
margin: 4px;
}
div#header { text-align: center; color: red; }
';
$css->parseString($strcss);
$arr = $css->toArray();
var_export($arr);
?>
To Inline
HTML_CSS::toInline() allow to integrate html tags
with styles.
Dissociate html code and presentation layout (CSS) is more than recommanded
Here is a basic example that show a white 'Hello World' on a black background :
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$css->setStyle('body', 'background-color', '#0c0c0c');
$css->setStyle('body', 'color', '#ffffff');
echo '<body style="' . $css->toInline('body') . '">';
echo '<p>Hello World</p>';
echo '</body>';
?>
To File
HTML_CSS::toFile() is probably the most interresting
solution. You can create a pure CSS file on the fly.
If file already exists, it will be replace without warning !
This script will load an existing style sheet and replace the body definition :
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$css->parseFile('example.css');
$css->setStyle('body', 'background-color', '#0c0c0c');
$css->setStyle('body', 'color', '#ffffff');
$css->toFile('example.css');
?>
To String
HTML_CSS::toString() is analogous to
HTML_CSS::toFile() except that result is capture
to a PHP variable rather than to a text/css file.
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$strcss = '
ul, body {
padding: 1em 2em;
}
';
$css->parseString($strcss);
$css->setGroupStyle(1, 'color', 'red');
$str = $css->toString();
echo $str;
// will display
// ul, body { padding: 1em 2em; color: red; }
?>
Display
HTML_CSS::display() is no more no less than just a
<?php
echo $css->toString();
?>with cache and charset management for browser output.
See also :
HTML_CSS::setCharset() and
HTML_CSS::setCache() functions.
Find definitions
Find definitions – searching for selectors and properties
In brief
One of features of HTML_CSS that was still missing to version less or equal
than 1.0.1 is ability to detect if a selector (or group of selectors), and/or
a property (or group of properties) was already defined.
This is now possible with method :
HTML_CSS::grepStyle()
Searching for a group of selectors
Let creates these definitions into progress2.css file :
#PB1.cellPB1I, #PB1.cellPB1A {
width: 15px;
height: 20px;
font-family: Courier, Verdana;
font-size: 8px;
float: left;
}
#PB1.progressBorderPB1 {
width: 172px;
height: 24px;
border-width: 1px;
border-style: solid;
border-color: #404040 #dfdfdf #dfdfdf #404040;
background-color: #CCCCCC;
}
.progressPercentLabelpct1PB1 {
width: 50px;
text-align: right;
background-color: transparent;
font-size: 11px;
font-family: Verdana, Tahoma, Arial;
font-weight: normal;
color: #000000;
}
.progressTextLabeltxt1PB1 {
text-align: left;
background-color: transparent;
font-size: 11px;
font-family: Verdana, Tahoma, Arial;
font-weight: normal;
color: #000000;
}
.cellPB1I {
background-color: #CCCCCC;
}
.cellPB1A {
background-color: #0033FF;
}
body {
background-color: #E0E0E0;
color: #000000;
font-family: Verdana, Arial;
}
Very easy with such script to find where is declared #PB1
class selectors (names like).
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$css->parseFile('progress2.css');
// find all selectors beginning with #PB1
$styles = $css->grepStyle('/^#PB1/');
echo '<pre>'; var_dump($styles); echo '</pre>';
?>
Searching for selectors that set a property
We still used the CSS definitions of previous example,
identified by progress2.css file :
Very easy with such script to find where is declared color
property.
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$css->parseFile('progress2.css');
// find all selectors that set the color property
$styles = $css->grepStyle('/./', '/^color$/');
echo '<pre>'; var_dump($styles); echo '</pre>';
?>
Reference guide
Handling options
HTML_CSS::__get
HTML_CSS::__get() – Get option for the class
Synopsis
require_once 'HTML/CSS.php';
mixed
HTML_CSS::__get
(
string
$option
)
Description
Return current value of an individual option. If option does not exist, returns value is NULL.
Parameter
-
string
$option -
Name of option to set
Throws
throws no exceptions thrown
Since
since version 1.4.0 (2007-12-13)
Note
This function can not be called statically.
HTML_CSS::__set
HTML_CSS::__set() – Set option for the class
Synopsis
require_once 'HTML/CSS.php';
void
HTML_CSS::__set
(
string
$option
,
string
$val
)
Description
Set an individual option value. Option must exist.
Parameter
-
string
$option -
Name of option to set
-
string
$val -
Value of option to set
Throws
throws no exceptions thrown
Since
since version 1.4.0 (2007-12-13)
Note
This function can not be called statically.
HTML_CSS::getCharset
HTML_CSS::getCharset() – Return the charset encoding string
Synopsis
require_once 'HTML/CSS.php';
string HTML_CSS::getCharset (
)
Description
By default, HTML_CSS uses iso-8859-1 encoding.
Throws
throws no exceptions thrown
See
Since
since version 0.2.0 (2003-07-31)
Note
This function can not be called statically.
HTML_CSS::getContentDisposition
HTML_CSS::getContentDisposition() – Return the Content-Disposition header
Synopsis
require_once 'HTML/CSS.php';
mixed HTML_CSS::getContentDisposition (
)
Description
Get value of Content-Disposition header (inline filename) used to display results
Throws
throws no exceptions thrown
Since
since version 1.3.0 (2007-10-22)
Note
This function can not be called statically.
Return value
returns boolean FALSE if no content disposition, otherwise string for inline filename
See
HTML_CSS::getOptions
HTML_CSS::getOptions() – Return all options for the class
Synopsis
require_once 'HTML/CSS.php';
array
HTML_CSS::getOptions
(
)
Description
Return all configuration options at once
Throws
throws no exceptions thrown
Since
since version 1.5.0 (2008-01-15)
Note
This function can not be called statically.
HTML_CSS::setCache
HTML_CSS::setCache() – Set cache flag
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::setCache (
bool $cache
= true
)
Description
Define if the document should be cached by the browser. Default to false.
Parameter
-
boolean
$cache -
(optional)
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
Since
since version 0.2.0 (2003-07-31)
Note
This function can not be called statically.
HTML_CSS::setCharset
HTML_CSS::setCharset() – Set charset value
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::setCharset (
string $type
= 'iso-8859-1'
)
Description
Define the charset for the file. Default to ISO-8859-1 because of CSS1 compatability issue for older browsers.
Parameter
-
string
$type -
(optional) Charset encoding; defaults to ISO-8859-1.
See
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
Since
since version 0.2.0 (2003-07-31)
Note
This function can not be called statically.
HTML_CSS::setContentDisposition
HTML_CSS::setContentDisposition() – Set Content-Disposition header
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::setContentDisposition (
boolean $enable
= true
, string $filename
= ''
)
Description
Defines the Content-Disposition filename for the browser output. Defaults to basename($_SERVER['PHP_SELF']).'.css'
Parameter
-
boolean
$enable -
(optional)
-
string
$filename -
(optional)
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
Since
since version 1.3.0 (2007-10-22)
See
see HTML_CSS::getContentDisposition()
Note
This function can not be called statically.
HTML_CSS::setLineEnd
HTML_CSS::setLineEnd() – Set lineend value
Synopsis
require_once 'HTML/CSS.php';
void
HTML_CSS::setLineEnd
(
string
$style
)
Description
Set the line end style to Windows, Mac, Unix or a custom string
Parameter
-
string
$style -
"win", "mac", "unix" or custom string.
Throws
throws no exceptions thrown
Since
since version 1.4.0 (2007-12-13)
Note
This function can not be called statically.
HTML_CSS::setOutputGroupsFirst
HTML_CSS::setOutputGroupsFirst() – Set groupsfirst flag
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::setOutputGroupsFirst (
bool $value
)
Description
Determine whether groups are output before elements or not
Parameter
-
boolean
$value -
flag to true if groups are output before elements, false otherwise
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
Since
since version 0.3.3 (2004-05-20)
Note
This function can not be called statically.
HTML_CSS::setSingleLineOutput
HTML_CSS::setSingleLineOutput() – Set oneline flag
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::setSingleLineOutput (
bool $value
)
Description
Determine whether definitions are output on a single line or multi lines
Parameter
-
boolean
$value -
flag to true if single line, false for multi lines
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
Since
since version 0.3.3 (2004-05-20)
Note
This function can not be called statically.
HTML_CSS::setTab
HTML_CSS::setTab() – Set tab value
Synopsis
require_once 'HTML/CSS.php';
void
HTML_CSS::setTab
(
string
$string
)
Description
Sets the string used to indent HTML
Parameter
-
string
$string -
String used to indent ("\11", "\t", ' ', etc.).
Throws
throws no exceptions thrown
Since
since version 1.4.0 (2007-12-13)
Note
This function can not be called statically.
HTML_CSS::setXhtmlCompliance
HTML_CSS::setXhtmlCompliance() – Set xhtml flag
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::setXhtmlCompliance (
bool $value
)
Description
Active or not the XHTML mode compliant
Parameter
-
boolean
$value -
flag to true if XHTML compliance needed, false otherwise
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
Since
since version 0.3.2 (2004-03-24)
Note
This function can not be called statically.
Handle selector and property values
HTML_CSS::getStyle
HTML_CSS::getStyle() – Return the value of a CSS property
Synopsis
require_once 'HTML/CSS.php';
mixed|PEAR_Error HTML_CSS::getStyle (
string $element
, string $property
)
Description
Get the value of a property to an identifed simple CSS element
Parameter
-
string
$element -
Element (or class) to be defined
-
string
$property -
Property defined
See
Throws
throws HTML_CSS_ERROR_INVALID_INPUT, HTML_CSS_ERROR_NO_ELEMENT, HTML_CSS_ERROR_NO_ELEMENT_PROPERTY
Since
since version 0.3.0 (2003-11-03)
Note
This function can not be called statically.
HTML_CSS::setStyle
HTML_CSS::setStyle() – Set or add a CSS definition
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::setStyle (
string $element
, string $property
, string $value
, bool $duplicates
= null
)
Description
Add or change a single value for an element property
Parameter
-
string
$element -
Element (or class) to be defined
-
string
$property -
Property defined
-
string
$value -
Value assigned
-
boolean
$duplicates -
(optional) Allow or disallow duplicates.
See
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
Since
since version 0.2.0 (2003-07-31)
Note
This function can not be called statically.
Example
<?php
require_once 'HTML/CSS.php';
// generate an instance
$css = new HTML_CSS();
// let's set some styles for <body>
$css->setStyle('body', 'background-color', '#0c0c0c');
$css->setStyle('body', 'color', '#ffffff');
// now for <h1>
$css->setStyle('h1', 'text-align', 'center');
$css->setStyle('h1', 'font', '16pt helvetica, arial, sans-serif');
// and finally for <p>
$css->setStyle('p', 'font', '12pt helvetica, arial, sans-serif');
// let's make <body> inherit from <p>
$css->setSameStyle('body', 'p');
// and let's put this into a tag:
echo '<body style="' . $css->toInline('body') . '">';
// will output:
// <body style="font:12pt helvetica, arial, sans-serif;background-color:#0c0c0c;color:#ffffff;">
?>
Grouping selectors
HTML_CSS::createGroup
HTML_CSS::createGroup() – Create a new CSS definition group
Synopsis
require_once 'HTML/CSS.php';
mixed|PEAR_Error HTML_CSS::createGroup (
string $selectors
, mixed $group
= null
)
Description
Create a new CSS definition group. Return an integer identifying the group.
Parameter
-
string
$selectors -
Selector(s) to be defined, comma delimited.
-
mixed
$group -
(optional) Group identifier. If not passed, will return an automatically assigned integer.
See
Throws
throws HTML_CSS_ERROR_INVALID_INPUT, HTML_CSS_ERROR_INVALID_GROUP
Since
since version 0.3.0 (2003-11-03)
Note
This function can not be called statically.
Example
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
// define styles
$css->setStyle('p', 'text-align', 'center');
$css->setStyle('p', 'color', '#ffffff');
$css->setStyle('p', 'text-align', 'left');
$css->setStyle('p', 'font', '16pt helvetica, arial, sans-serif');
$css->setStyle('p', 'font', '12pt helvetica, arial, sans-serif');
// create a selectors group
$groupID = 'myGroup';
$groupID = $css->createGroup('p, a', $groupID);
// define styles of this new group
$css->setGroupStyle($groupID, 'font', '12pt helvetica, arial, sans-serif');
// display result
echo $css->toString();
// will output:
/*
p, a {
font: 12pt helvetica, arial, sans-serif;
}
p {
text-align: left;
color: #ffffff;
font: 12pt helvetica, arial, sans-serif;
}
*/
?>
HTML_CSS::unsetGroup
HTML_CSS::unsetGroup() – Remove a CSS definition group
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::unsetGroup (
mixed $group
)
Description
Remove a CSS definition group. Use the same identifier as for group creation.
Parameter
-
mixed
$group -
CSS definition group identifier
See
Throws
throws HTML_CSS_ERROR_INVALID_INPUT, HTML_CSS_ERROR_NO_GROUP
Since
since version 0.3.0 (2003-11-03)
Note
This function can not be called statically.
HTML_CSS::getGroupStyle
HTML_CSS::getGroupStyle() – Return CSS definition for a CSS group
Synopsis
require_once 'HTML/CSS.php';
mixed|PEAR_Error HTML_CSS::getGroupStyle (
mixed $group
, string $property
)
Description
Get the CSS definition for group created by setGroupStyle()
Parameter
-
mixed
$group -
CSS definition group identifier
-
string
$property -
Property defined
See
Throws
throws HTML_CSS_ERROR_INVALID_INPUT, HTML_CSS_ERROR_NO_GROUP, HTML_CSS_ERROR_NO_ELEMENT
Since
since version 0.3.0 (2003-11-03)
Note
This function can not be called statically.
HTML_CSS::setGroupStyle
HTML_CSS::setGroupStyle() – Set or add a CSS definition for a CSS group
Synopsis
require_once 'HTML/CSS.php';
void|int|PEAR_Error HTML_CSS::setGroupStyle (
mixed $group
, string $property
, string $value
, bool $duplicates
= null
)
Description
Define the new value of a property for a CSS group. The group should exist. If not, use HTML_CSS::createGroup() first
Parameter
-
mixed
$group -
CSS definition group identifier
-
string
$property -
Property defined
-
string
$value -
Value assigned
-
boolean
$duplicates -
(optional) Allow or disallow duplicates.
Return value
returns Returns an integer if duplicates are allowed.
See
Throws
throws HTML_CSS_ERROR_INVALID_INPUT, HTML_CSS_ERROR_NO_GROUP
Since
since version 0.3.0 (2003-11-03)
Note
This function can not be called statically.
HTML_CSS::addGroupSelector
HTML_CSS::addGroupSelector() – Add a selector to a CSS definition group.
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::addGroupSelector (
mixed $group
, string $selectors
)
Description
Add a selector to a CSS definition group
Parameter
-
mixed
$group -
CSS definition group identifier
-
string
$selectors -
Selector(s) to be defined, comma delimited.
Throws
throws HTML_CSS_ERROR_NO_GROUP, HTML_CSS_ERROR_INVALID_INPUT
Since
since version 0.3.0 (2003-11-03)
Note
This function can not be called statically.
Example
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
// define styles
$g = $css->createGroup('body, html');
$css->setGroupStyle($g, 'margin', '2px');
$css->setGroupStyle($g, 'padding', '0');
$css->setGroupStyle($g, 'border', '0');
// display intermediate result
echo $css->toString();
// will output:
/*
body, html {
margin: 2px;
padding: 0;
border: 0;
}
*/
// did not reflect a real usage, it's only a study case purpose
$css->removeGroupSelector($g, 'body');
$css->addGroupSelector($g, '.large');
$css->setGroupStyle($g, 'border', 'solid thin');
// display final result
echo $css->toString();
// will output:
/*
html, .large {
margin: 2px;
padding: 0;
border: solid thin;
}*/
?>
HTML_CSS::removeGroupSelector
HTML_CSS::removeGroupSelector() – Remove a selector from a group
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::removeGroupSelector (
mixed $group
, string $selectors
)
Description
Definitively remove a selector from a CSS group
Parameter
-
mixed
$group -
CSS definition group identifier
-
string
$selectors -
Selector(s) to be removed, comma delimited.
Throws
throws HTML_CSS_ERROR_NO_GROUP, HTML_CSS_ERROR_INVALID_INPUT
Since
since version 0.3.0 (2003-11-03)
Note
This function can not be called statically.
HTML_CSS::setSameStyle
HTML_CSS::setSameStyle() – Apply same styles on two selectors
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::setSameStyle (
string $new
, string $old
)
Description
Set or change the properties of a new basic selector (not group) to the values of an existing selector
Parameter
-
string
$new -
New selector that should share the same definitions
-
string
$old -
Selector that is already defined
Throws
throws HTML_CSS_ERROR_INVALID_INPUT, HTML_CSS_ERROR_NO_ELEMENT
Since
since version 0.2.0 (2003-07-31)
Note
This function can not be called statically.
Example
see HTML_CSS::setStyle() , if you want only to apply the same style as a basic selector.
see HTML_CSS::createGroup() , if you want to apply the same style to a list of selectors.
Parsing data sources
HTML_CSS::parseString
HTML_CSS::parseString() – Parse a string
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::parseString (
string $str
, bool $duplicates
= null
)
Description
Parse a string that contains CSS information
Parameter
-
string
$str -
text string to parse
-
boolean
$duplicates -
(optional) Allows or disallows duplicate style definitions
See
see HTML_CSS::createGroup() , HTML_CSS::setGroupStyle() , HTML_CSS::setStyle()
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
Since
since version 0.3.0 (2003-11-03)
Note
This function can not be called statically.
HTML_CSS::parseFile
HTML_CSS::parseFile() – Parse file content
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::parseFile (
string $filename
, bool $duplicates
= null
)
Description
Parse a file that contains CSS information
Parameter
-
string
$filename -
file to parse
-
boolean
$duplicates -
(optional) Allow or disallow duplicates.
See
Throws
throws HTML_CSS_ERROR_INVALID_INPUT, HTML_CSS_ERROR_NO_FILE
Since
since version 0.3.0 (2003-11-03)
Note
This function can not be called statically.
HTML_CSS::parseData
HTML_CSS::parseData() – Parse multiple data sources
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::parseData (
array $styles
, bool $duplicates
= null
)
Description
Parse data sources, file(s) or string(s), that contains CSS information
Parameter
-
array
$styles -
data sources to parse
-
boolean
$duplicates -
(optional) Allow or disallow duplicates.
See
see HTML_CSS::parseString() , HTML_CSS::parseFile()
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
Since
since version 1.0.0RC2 (2005-12-15)
Note
This function can not be called statically.
Checking data sources
HTML_CSS::validate
HTML_CSS::validate() – Validate a CSS data source
Synopsis
require_once 'HTML/CSS.php';
boolean|PEAR_Error
HTML_CSS::validate
(
array
$styles
,
array
&$messages
)
Description
Execute the W3C CSS validator service on each data source (filename or string) given by parameter $styles.
Parameter
-
array
$styles -
Data sources to check validity
-
array
&$messages -
Error and Warning messages issue from W3C CSS validator service
Throws
throws HTML_CSS_ERROR_INVALID_INPUT, HTML_CSS_ERROR_INVALID_DEPS, HTML_CSS_ERROR_INVALID_SOURCE
Since
since version 1.5.0 (2008-01-15)
Note
This function can not be called statically.
Output
HTML_CSS::toArray
HTML_CSS::toArray() – Return the CSS contents in an array
Synopsis
require_once 'HTML/CSS.php';
array HTML_CSS::toArray (
)
Description
Return the full contents of CSS data sources (parsed) in an array
Throws
throws no exceptions thrown
Since
since version 0.2.0 (2003-07-31)
Note
This function can not be called statically.
HTML_CSS::toInline
HTML_CSS::toInline() – Return a string-properties for style attribute of an HTML element
Synopsis
require_once 'HTML/CSS.php';
string|PEAR_Error HTML_CSS::toInline (
string $element
)
Description
Generate and return the CSS properties of an element or class as a string for inline use.
Parameter
-
string
$element -
Element or class for which inline CSS should be generated
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
Since
since version 0.2.0 (2003-07-31)
Note
This function can not be called statically.
HTML_CSS::toFile
HTML_CSS::toFile() – Generate CSS and stores it in a file
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error HTML_CSS::toFile (
string $filename
)
Description
Generate current parsed CSS data sources and write result in a user file
Parameter
-
string
$filename -
Name of file that content the stylesheet
See
Throws
throws HTML_CSS_ERROR_INVALID_INPUT, HTML_CSS_ERROR_WRITE_FILE
Since
since version 0.3.0 (2003-11-03)
Note
This function can not be called statically.
HTML_CSS::toString
HTML_CSS::toString() – Return current CSS parsed data as a string
Synopsis
require_once 'HTML/CSS.php';
string HTML_CSS::toString (
)
Description
Generate current parsed CSS data sources and return result as a string
Throws
throws no exceptions thrown
Since
since version 0.2.0 (2003-07-31)
Note
This function can not be called statically.
HTML_CSS::display
HTML_CSS::display() – Output CSS Code
Synopsis
require_once 'HTML/CSS.php';
void HTML_CSS::display (
)
Description
Send the stylesheet content to standard output, handling cacheControl and contentDisposition headers
Throws
throws no exceptions thrown
See
Since
since version 0.2.0 (2003-07-31)
Note
This function can not be called statically.
Searching for selectors and/or properties
HTML_CSS::grepStyle
HTML_CSS::grepStyle() – Retrieve styles corresponding to an element filter
Synopsis
require_once 'HTML/CSS.php';
array|PEAR_Error HTML_CSS::grepStyle (
string $elmPattern
, string $proPattern
)
Description
Return array entries of styles that match patterns (Perl compatible)
Parameter
-
string
$elmPattern -
Element or class pattern to retrieve
-
string
$proPattern -
(optional) Property pattern to retrieve
See
see Regular Expression Functions (Perl-Compatible)
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
Since
since version 1.1.0 (2007-01-01)
Note
This function can not be called statically.
Handling At-Rules
HTML_CSS::getAtRulesList
HTML_CSS::getAtRulesList() – Return list of supported At-Rules
Synopsis
require_once 'HTML/CSS.php';
void
HTML_CSS::getAtRulesList
(
)
Description
Return the list of At-Rules supported by API 1.5.0 of HTML_CSS
Throws
throws no exceptions thrown
Since
since version 1.5.0 (2008-01-15)
Note
This function can not be called statically.
Example
<?php
require_once 'HTML/CSS.php';
$list = $css->getAtRulesList();
var_export($list);
// will output:
//
// array (
// 0 => '@charset',
// 1 => '@font-face',
// 2 => '@import',
// 3 => '@media',
// 4 => '@page',
// 5 => '@namespace',
// )
?>
HTML_CSS::createAtRule
HTML_CSS::createAtRule() – Create a new simple declarative At-Rule
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error
HTML_CSS::createAtRule
(
string
$atKeyword
,
string
$arguments
= ''
,
bool
$duplicates
= null
)
Description
Create a simple at-rule without declaration style blocks. That include @charset, @import and @namespace
Parameter
-
string
$atKeyword -
at-rule keyword
-
string
$arguments -
argument list for @charset, @import or @namespace
-
boolean
$duplicates -
(optional) Allow or disallow duplicates
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
See
Since
since version 1.5.0 (2008-01-15)
Note
This function can not be called statically.
HTML_CSS::unsetAtRule
HTML_CSS::unsetAtRule() – Remove an existing At-Rule
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error
HTML_CSS::unsetAtRule
(
string
$atKeyword
)
Description
Remove an existing and supported at-rule. See HTML_CSS::getAtRulesList() for a full list of supported At-Rules.
Parameter
-
string
$atKeyword -
at-rule keyword
Throws
throws HTML_CSS_ERROR_INVALID_INPUT, HTML_CSS_ERROR_NO_ATRULE
Since
since version 1.5.0 (2008-01-15)
Note
This function can not be called statically.
HTML_CSS::getAtRuleStyle
HTML_CSS::getAtRuleStyle() – Get style value of an existing At-Rule
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error
HTML_CSS::getAtRuleStyle
(
string
$atKeyword
,
string
$arguments
,
string
$selectors
,
string
$property
)
Description
Retrieve arguments or style value of an existing At-Rule. See HTML_CSS::getAtRulesList() for a full list of supported At-Rules.
Parameter
-
string
$atKeyword -
at-rule keyword
-
string
$arguments -
argument list (optional for @font-face)
-
string
$selectors -
selectors of declaration style block (optional for @media, @page, @font-face)
-
string
$property -
property of a single declaration style block
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
See
see HTML_CSS::setAtRuleStyle()
Since
since version 1.5.0 (2008-01-15)
Note
This function can not be called statically.
HTML_CSS::setAtRuleStyle
HTML_CSS::setAtRuleStyle() – Define a conditional/informative At-Rule
Synopsis
require_once 'HTML/CSS.php';
void|PEAR_Error
HTML_CSS::setAtRuleStyle
(
string
$atKeyword
,
string
$arguments
,
string
$selectors
,
string
$property
,
string
$value
,
bool
$duplicates
= null
)
Description
Set arguments and declaration style block for at-rules that follow : "@media, @page, @font-face"
Parameter
-
string
$atKeyword -
at-rule keyword
-
string
$arguments -
argument list (optional for @font-face)
-
string
$selectors -
selectors of declaration style block (optional for @media, @page, @font-face)
-
string
$property -
property of a single declaration style block
-
string
$value -
value of a single declaration style block
-
boolean
$duplicates -
(optional) Allow or disallow duplicates
Throws
throws HTML_CSS_ERROR_INVALID_INPUT
See
see HTML_CSS::getAtRuleStyle()
Since
since version 1.5.0 (2008-01-15)
Note
This function can not be called statically.
Handling error
Error Handler
Error Handler – Flexible error handler plug-in system
Introduction
The HTML_CSS package is implemented with a flexible error handler plug-in system. You may use any error handler that you want. Using PEAR_Error object (default), but also the PEAR_ErrorStack package, or any other error handler you might want to plug in.
Without any configuration, each HTML_CSS API error (basic or exception) will raise a HTML_CSS_Error object that will be return to call script (user script).
Easy to distinct basic PEAR_Error from other PEAR packages to HTML_CSS errors, even if there is a better and more robust solution:
HTML_CSS::isError(). But also provide a unique way to retrieve the level of error (warning, error, exception) with theHTML_CSS_Error::getLevel()method.
As usual you can use the PEAR error API as well.
<?php
require_once 'HTML/CSS.php';
$css = new HTML_CSS();
$result = $css->setStyle('div', 'color', 5);
if (PEAR::isError($result)) {
// do something when an error is raised
}
?>and output to screen will give something like :
Exception*: invalid input, parameter #3 "$value" was expecting "string",
instead got "integer"** in html_css->setstyle (file [path_to]\[filename] on line 6)***
| * |
error level |
| ** |
message body with context informations |
| *** |
call context |
Perhaps this standard behavior is not what you want. Don't worry, you can change everything :
- display or ignore the error
- display or hide part of message (error level, body, context)
HTML_CSS obey at display_errors and log_errors protocol
Configuring a Handler
A error handler's configuration is determined by the arguments used in its construction. Here's an overview of these parameters.
<?php
require_once 'HTML/CSS.php';
$errorConf = array('error_handler' => 'myErrorHandler',
'push_callback' => 'myError',
// ... more options
);
$css = new HTML_CSS(null, $errorConf);
?>
| Option | Type | Description |
|---|---|---|
| error_handler | callback |
A valid callback (function) to manage errors raised by the
HTML_CSS::raiseError() method.
Default is: HTML_CSS::_errorHandler
|
| push_callback | callback | A valid callback (function) that decides to following action. Default return: PEAR_ERROR_DIE if exception, NULL otherwise. |
| error_callback | callback | A valid callback (function) that decides to call a real free user function. Default call: none |
| message_callback | callback |
A valid callback (function) to control message generation.
Default is: HTML_CSS_Error::_msgCallback
|
| context_callback | callback |
A valid callback (function) to control error context generation.
Default is: HTML_CSS_Error::getBacktrace
|
| handler | mixed | any handler-specific settings |
Controlling error generation
There are many scenarios in which fine-grained control over error raising is absolutely necessary.
The first level to control error generation is the php.ini directives
display_errors and log_errors.
When these directives are set to TRUE, then browser and file outputs are
effective.
If you want to ignore all errors raised (no display, no logs) and avoid to include PEAR core class, then you should have something like :
<?php require_once 'HTML/CSS.php'; function myErrorHandler() { return null; } $errorConf = array('error_handler' => 'myErrorHandler'); $css = new HTML_CSS(null, $errorConf); // ... ?>
Note for users of HTML_CSS 1.4.0 or greater
You may want to decide to print (yes/no), log (yes/no) error messages with a full free user function local to HTML_CSS
<?php require_once 'HTML/CSS.php'; function myErrorAction($css_error) { // do what you want: print and/or log $css_error instance of HTML_CSS_Error object } $errorConf = array('error_callback' => 'myErrorAction'); $css = new HTML_CSS(null, $errorConf); // ... ?>rather than using global PEAR error handler (PEAR::setErrorHandling, PEAR::pushErrorHandling, PEAR::popErrorHandling).
<?php require_once 'HTML/CSS.php'; function myErrorAction($css_error) { // do what you want: print and/or log $css_error instance of HTML_CSS_Error object } PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'myErrorAction'); $css = new HTML_CSS(); // ... ?>
With push_callback option, you can decides to stop script execution (as done with exceptions by default: returns PEAR_ERROR_DIE constant), or continue without filtering (returns NULL).
If you want to write your own callback function for the push_callback option, this one should have two arguments: first one will get the error code, and second will get error level. These are all the necessary informations to do a filtering. Example that follow show how to be aware that a script use wrong argument data type.
<?php
require_once 'HTML/CSS.php';
function myErrorFilter($code, $level)
{
if ($code === HTML_CSS_ERROR_INVALID_INPUT) {
error_log('script: '.__FILE__.' used wrong argument data type', 1, 'admin@yoursite.com');
}
return null;
}
$errorConf = array('push_callback' => 'myErrorFilter');
$css = new HTML_CSS(null, $errorConf);
// ...
?>
Error Context Display
In some cases, you may want to customize error generation. For instance, for each error (basic/exception), it is useful to include file, line number, and class/function context information in order to trace it. The default option will be sufficient for most cases but you want perhaps customize the output format (render) of context information.
With this example we will change display and log renders.
<?php
require_once 'HTML/CSS.php';
$displayConfig = array(
'lineFormat' => '<b>%1$s</b>: %2$s<br />%3$s',
'contextFormat' => '<b>File:</b> %1$s <br />'
. '<b>Line:</b> %2$s <br />'
. '<b>Function:</b> %3$s '
);
$logConfig = array(
'lineFormat' => '%1$s %2$s [%3$s] %4$s',
'timeFormat' => '%b'
);
$prefs = array(
'handler' => array('display' => $displayConfig,
'log' => $logConfig
));
$css = new HTML_CSS(null, $prefs);
// ...
$result = $css->setStyle('div', 'color', 5);
?>
Display render will give something like:
Exception****: invalid input, parameter #3 "$value" was expecting "string", instead got "integer"*****
File: [path_to]\[filename] ******
Line: 22
Function: html_css->setstyle
| * |
error level |
| ** |
message body with context informations |
| *** |
call context (file, line, function) |
Log render will give something like:
Jun 127.0.0.1******* [exception********] invalid input, parameter #3 "$value" was expecting "string", instead got "integer"*********
| * |
client ip address and execution date |
| ** |
error level |
| *** |
message body with context informations |
To have both display and log output, check the
php.inidisplay_errors and log_errors values : must be set to TRUE.
Let review, step by step, how to get such results.
Remember that with default classes, there are two drivers : display and log that have both their own configuration parameters. You can override these parameters values with the handler entry in the hash of second argument of the HTML_CSS class constructor.
We did it here with the $prefs variable; it's a two key
associative array. First key display defines the display driver
values, and the second key log defines the log driver values.
Review the display driver custom values. Only two keys:
- lineFormat
- contextFormat
are redefined, thats means remains key
- eol
keep its default value. See table below.
| Parameter | Type | Default | Description |
|---|---|---|---|
| eol | string | <br />\n | The end-on-line character sequence |
| lineFormat | string | <b>%1$s</b>: %2$s %3$s | Log line format specification:
|
| contextFormat | string | in <b>%3$s</b> (file <b>%1$s</b> on line <b>%2$s</b>) | Context format (class, file, line) specification:
|
If you don't wish to see context information in the error message, then remove the parameter %3$ in the lineFormat option even if contextFormat is set.
Review now the log driver custom values. Only two keys
- lineFormat
- timeFormat
are redefined, thats means six remains keys
- eol
- contextFormat
- ident
- message_type
- destination
- extra_headers
keep their default values. See table below.
| Parameter | Type | Default | Description |
|---|---|---|---|
| eol | string | \n | The end-on-line character sequence |
| lineFormat | string | %1$s %2$s [%3$s] %4$s %5$s | Log line format specification:
|
| contextFormat | string | in %3$s (file %1$s on line %2$s) | Context format (class, file, line) specification:
|
| timeFormat | string | %b %d %H:%M:%S | Time stamp format used by strftime |
| ident | string | REMOTE_ADDR | Client IP |
| message_type | string | 3 | Destination type used by error_log |
| destination | string | html_css_error.log | Destination name used by error_log |
| extra_headers | string | NULL | Extra headers depending of destination type |
If you don't wish to see context information in the error message, then remove the parameter %5$ in the lineFormat option even if contextFormat is set.
Custom Error Message Generation
There are two methods of HTML_CSS_Error designed for use with generating error messages efficiently. To use them, you must set the options below in the HTML_CSS class constructor (argument #2):
Option: message_callback
The default message handling callback
(HTML_CSS_Error::_getErrorMessage)
get an array mapping error codes to error message templates, like so:
<?php
$messages = array(
HTML_CSS_ERROR_UNKNOWN =>
'unknown error',
HTML_CSS_ERROR_INVALID_INPUT =>
'invalid input, parameter #%paramnum% '
. '"%var%" was expecting '
. '"%expected%", instead got "%was%"'
);
?>Basically, if a variable name is enclosed in percent signs (%), it will be replaced with the value passed in the associative array.
Option: context_callback
The default context handling callback
(HTML_CSS_Error::getBackTrace)
gets an array of execution functions and discovers where the error was generated.