views:

43

answers:

2

CONTEXT:

My project is a CMS website, and each user's CSS is held in a database table. Fields are:

int     id            primary
int     site_id       index
string  selector
string  property
string  value
bool    important

When a user's website is pulled up, it's a simple query:

SELECT * FROM css_table WHERE site_id = $this_site_id

And using PHP the rows are processed and turned into proper CSS.

THE QUESTION:

I need to go in reverse now.

There will be a Advanced CSS mode that will give the administrators a raw CSS editor. The table rows will be processed once more to populate the textarea and allow editing. Now it has to get back into the database. How do I process this new CSS back into separate, insertable fields?

A: 

You should look for a CSS parser (unless you want to write your own):
http://csstidy.sourceforge.net/
http://www.phpclasses.org/package/1289-PHP-CSS-parser-class.html

or just Google, there are tons of them.

dark_charlie
This is what I initially thought, however it will be extremely difficult to match up the parsed CSS to a row within the database.
evolve
The CSS Parser is what I needed, thank you. The link you provided required registration, so here's a better source:http://github.com/dbr/so_scripts/blob/master/csssparser.php
Curtis
@evolve: I posted the code to do exactly that as an additional answer.
Curtis
@Curtis Great piece of work, this will be certainly useful for many people.
dark_charlie
+1  A: 

Using the CSS Parser (github) suggested by dark_charlie, I was able to come up with the following code to turn CSS back into SQL.

<?
require('cssparser.php');

$cssp = new cssparser;
$cssp->Parse('test.css');

$query = 'INSERT INTO css_table (`selector`, `property`, `value`) VALUES ';

foreach($cssp->css as $selector => $properties) {
    foreach($properties as $property => $value) {
        $query .= "('$selector', '$property', '$value'), ";
    }
}

$query = substr_replace($query, ';', -2);
echo $query; // Testing
?>

Addendum: After using the method I developed here, I quickly realized how unpractical it was to have every property inserted as a new row. The CSS for a single phpbb board is over a 1000 rows, and to multiply that for each independent board was insane.

The better alternative for my situation was to simply use a single mediumtext field and place the raw CSS in the table. To modify properties, I parse the CSS into an array, modify properties as needed, and parse the array back to CSS and update the DB with the new CSS.

For the "Advanced CSS" editing mode, it's a simple fetch/update now since the DB is holding plain CSS.

Curtis