Intekhab Rizvi

PHP CSS file parser

Read a CSS file or string into a PHP array, search and change rules, then save or export the result.

Language
PHP
Works with
Plain PHP, CodeIgniter 2 and 3
Licence
MIT

Overview

Cssparser is a small PHP class. It reads a CSS file or a CSS string into a PHP array, gives you methods to find, add, rename, update and remove rules and properties, and writes everything back as CSS, either to the file or as a string.

Compatibility

  • Plain PHP, or CodeIgniter 2 and 3 as a library.
  • A single file (Cssparser.php). It is not published on Packagist, so there is no composer require.

Installation

Plain PHP

require('Cssparser.php');
$css = new Cssparser();

CodeIgniter

  1. Put Cssparser.php in application/libraries/.
  2. Load it in a controller:
    $this->load->library('cssparser');
    $this->cssparser->read_from_file($folder . '/css/custom.css');
    

Usage

$css = new Cssparser();
$css->read_from_file('myfolder/myfile.css');

// change a property, add a rule, remove another
$css->update_property('#bodywrapper', 'max-width', '600px');
$css->add_parent('#banner', array('background-color' => '#FFF'));
$css->remove_parent('#old-rule');

// write back to the same file, or get the CSS as a string
$css->save();
$output = $css->export_css();

Method reference

MethodWhat it does
read_from_file, read_from_stringParse a CSS file or string into a PHP array
find_parentFind a rule by selector
find_parent_by_propertyFind rules that use a property
find_parent_by_valueFind rules that use a value
find_property_value_pairFind rules by property and value
add_parent, remove_parent, rename_parentAdd, remove or rename a rule
add_property, update_property, remove_propertyChange properties inside a rule
export_cssReturn the current CSS as a string
saveWrite the CSS back to the file passed to read_from_file