开发者

Separating the components of CSS for database entry

开发者 https://www.devze.com 2023-01-10 05:29 出处:网络
CONTEXT: My project is a CMS website, and each user\'s CSS is held in a database table. Fields are: intidprimary

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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号