Open-source project
MyIntervals/PHP-CSS-Parser avatar
MyIntervals/PHP-CSS-Parser

PHP-CSS-Parser for PHP CSS Transformations

A Parser for CSS Files written in PHP. Allows extraction of CSS files into a data structure, manipulation of said structure and output as (optimized) CSS

1,825 stars153 forksPHPMIT

At a glance

What is it?
MyIntervals/PHP-CSS-Parser converts CSS into a mutable object model for PHP applications that need to inspect, rewrite, and render stylesheets. It suits programmatic selector and declaration changes, but its multibyte support remains incomplete.
Who is it for?
PHP-CSS-Parser fits PHP applications that need structured CSS transformations rather than plain-text replacements. It is a poor choice for uncontrolled multibyte input or workflows that require documented rollback behavior.
Can I use it commercially?
Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
Is it still maintained?
Yes. The repository received new commits within the last day.
What is it written in?
Mainly PHP, according to GitHub's language statistics.

Answers come from the project's GitHub data, last synced on November 7, 2026, and from our analysis. They are not legal advice.

From daily snapshots

Star history

  • MyIntervals/PHP-CSS-Parser1,825 ★ · -1
Star history
Repository2026-10-162026-11-07
MyIntervals/PHP-CSS-Parser1.8k1.8k

-1 Stars in the last 22 days, measured from the daily GitHub snapshot. Compare with other projects

Editorial analysis

Why PHP-CSS-Parser Exists

PHP-CSS-Parser addresses a specific problem in PHP applications: stylesheets often need semantic changes rather than textual substitutions. A tool that searches for strings cannot reliably distinguish a selector from a declaration value, an at-rule from a declaration block, or a quoted string from an identifier. This library turns CSS into a hierarchy of PHP objects that can be inspected and changed before output.

The intended users are PHP developers building themes, style processors, CMS integrations, or other server-side tools that need to prefix selectors, alter values, remove rules, or collect CSS constructs. Based on the repository layout, the package includes its library under `src/`, tests, documentation, Composer metadata, and a `bin/` directory. Its primary language and package type align with that server-side use case.

The scope is CSS processing, not browser rendering or a full CSS layout engine. The object model distinguishes containers, declaration blocks, individual declarations, selectors, primitive values, function arguments, imports, and charset declarations. That makes it possible to reason about structures such as media rules instead of treating every `{...}` segment as interchangeable text.

This approach is less suitable when a transformation can be performed safely with direct string replacement, especially for a very small, fixed edit. Creating and navigating an object graph adds work. PHP-CSS-Parser becomes more relevant when the application must understand multiple node types or perform repeated transformations over stylesheets.

How the CSS Object Model Is Structured

The parser receives CSS text through `\Sabberworm\CSS\Parser` and returns a document structure after `parse()` is called. The README shows that a file can be read into the constructor with `file_get_contents()`. The resulting object graph mainly contains `CSSList`, `RuleSet`, `Rule`, `Selector`, and `Value`, with `Import` and `Charset` covering less common document entries.

`CSSList` is the generic container. It may hold declaration blocks, at-rules, imports, charset declarations, or other `CSSList` objects. Code reads its entries through `getContents()` and checks the concrete type with `instanceof`. New content can be added with `append($oItem)`. Nesting is significant because selectors and at-rules can occur inside containers rather than only at the document root.

`RuleSet` holds declarations. A `DeclarationBlock` represents selector-bound declarations, while `AtRuleSet` covers generic at-rules not handled by specialized classes such as `Import`, `Charset`, or media containers. Rule operations include `addRule(Rule $rule)`, `getRules()`, and `removeRule($rule)`. A rule consists of a string key and a `Value`, so callers can address declarations by object or by rule name rather than editing serialized CSS.

Values have their own hierarchy. `Size` separates numeric size from its unit. `Color` normalizes supported color input into component storage, while `CSSString` distinguishes quoted strings and always renders with double quotes. `URL` renders in `URL("")` notation. `RuleValueList` handles separated value groups, and `CSSFunction` stores function names and arguments. This model exposes CSS structure, although serialization is not guaranteed to preserve the original text formatting.

Composer Installation and a First Selector Rewrite

The README gives Composer as the installation method. This command adds `sabberworm/php-css-parser` to a PHP application's dependencies:

bash
composer require sabberworm/php-css-parser

After installation, a concrete first use is to prepend an ID selector to every declaration block. This example reads `$css` into the parser, calls `parse()`, and updates each selector with `setSelector()`:

php
$myId = "#my_id";
$parser = new \Sabberworm\CSS\Parser($css);
$cssDocument = $parser->parse();
foreach ($cssDocument->getAllDeclarationBlocks() as $block) {
    foreach ($block->getSelectors() as $selector) {
        $selector->setSelector($myId.' '.$selector->getSelector());
    }
}

`getAllDeclarationBlocks()` finds declaration blocks regardless of nesting depth, so the example does not need to reproduce the document's container hierarchy manually. Each selector receives the literal prefix `"#my_id "`. The README presents this as a manipulation example, but it does not show the subsequent rendering call in the displayed text, so no rendering method should be assumed without consulting the API documentation.

A developer integrating the transformation should keep the original stylesheet text separately until the output behavior has been checked against the application. That is not a documented rollback feature in PHP-CSS-Parser. It is a caller-controlled way to retain an unmodified input if the transformed result does not meet project requirements.

Charset, Strict Mode, and Multibyte Trade-offs

UTF-8 is the default charset, which means a settings object is unnecessary when that default is suitable. The configured charset is used only when the CSS file does not contain an `@charset` declaration. For files that require a different fallback charset, the README provides `Settings::create()->withDefaultCharset()`:

php
$settings = \Sabberworm\CSS\Settings::create()
    ->withDefaultCharset('windows-1252');
$parser = new \Sabberworm\CSS\Parser($css, $settings);

Strict parsing changes recovery behavior. By default, the parser tries to ignore invalid or unknown constructs and continue. `Settings::create()->beStrict()` makes it throw an exception instead. That is useful when malformed CSS should stop processing, but the README also warns that strict mode disables a workaround for the unquoted legacy IE-specific `filter` rule.

Multibyte support has a direct trade-off. The setting `withMultibyteSupport(false)` makes the parser use regular string functions instead of `mb_*` functions, with the stated aim of faster parsing. The README says this should work in most cases, including UTF-8 files when multibyte characters occur inside string literals, but explicitly advises against using it with input the caller does not control because the behavior is not thoroughly covered by tests.

The broader limitation appears in the project's To-Do list: real multibyte support is unfinished. The stated support covers multibyte charsets whose first 255 code points take up only one byte and are identical with ASCII, which includes UTF-8. Applications handling arbitrary multibyte syntax should treat parser compatibility as something to verify rather than assume.

Optimization Versus a Text-Based CSS Tool

PHP-CSS-Parser describes its output as optimized CSS, but it is not presented as a command-line minifier in the README. Its distinguishing approach is parsing. It recognizes document containers, rule sets, selectors, declaration values, functions, imports, and charset nodes, then provides methods for navigating and changing them. That structural understanding is the reason to choose it over regular expressions or string concatenation.

A regex-based or dedicated text minifier has a different design. Such a tool generally scans source text and rewrites whitespace, comments, or selected declarations without requiring the caller to navigate a PHP object graph. It can be a better fit for a simple batch minification command, especially when edits do not require semantic inspection. It is less suitable for transformations that depend on node type or selector relationships.

The parser-based route also changes expectations around formatting. `Color`, `CSSString`, and `URL` have documented rendering forms, and those forms are not always identical to the input spelling. Applications that preserve author formatting exactly should not interpret the word "parser" as a guarantee of lossless round trips. The README does not define a formatting-preservation mode or document rollback behavior.

For PHP-CSS-Parser, the relevant comparison is not simply "structured versus smaller." The question is whether the application needs semantic CSS operations enough to justify parsing and object manipulation. If the goal is only output compression, a CSS minifier is the closer category. If the goal is to change selectors or declarations in application logic, the object model provides operations that a text-only pipeline does not document.

Maintenance, Releases, and MIT Usage

The repository is not archived, and the last push was on 2026-10-15. That date places it within the six-month maintenance window used for this review. Recent release notes also document version activity. Version 9.3.0 added support for modern CSS at-rules and included an autoloading bug fix. Version 9.4.0 focused on deprecations and bug fixes, while version 9.5.0 added support for PHP 8.6. These release notes provide evidence of recent project changes, but they do not establish compatibility with every PHP version, CSS feature, or extension used by a consumer.

The upgrade surface is shaped by the major version and by deprecated APIs. An application moving between versions should review `CHANGELOG.md` rather than assuming that all parser behavior or object construction is unchanged. The repository also contains `CONTRIBUTING.md`, `CODE_OF_CONDUCT.md`, tests, and workflow configuration, but the README does not document the exact test command or a semantic-versioning compatibility policy.

The project uses the MIT license. That is a permissive license identifier, but this review does not interpret its obligations or provide legal advice. Consumers still need to review the repository's `LICENSE` file and their own distribution and compliance requirements.

The last push date is a maintenance fact, not proof that every CSS construct is supported. The README's To-Do list remains more relevant to adoption risk: convenience methods are unfinished, real multibyte support is incomplete, and named colors are still listed as future work.

Editorial conclusion

PHP-CSS-Parser fits PHP applications that need structured CSS transformations rather than plain-text replacements. It is a poor choice for uncontrolled multibyte input or workflows that require documented rollback behavior. Before adoption, verify that your stylesheets parse under the intended charset settings and that object-level changes produce acceptable rendered CSS.

Frequently asked questions

How do I install PHP-CSS-Parser?

The README gives `composer require sabberworm/php-css-parser` as the installation command. It then documents constructing `\Sabberworm\CSS\Parser` with CSS text and calling `parse()`.

Can PHP-CSS-Parser change CSS selectors?

Yes. The README shows calling `getAllDeclarationBlocks()`, iterating over each block's selectors, and changing a selector with `setSelector()`. The example prepends `#my_id` to every selector.

Does PHP-CSS-Parser support multibyte CSS?

The README says real multibyte support is still a To-Do item. It states that UTF-8 fits the currently supported case and warns against disabling multibyte support for input the caller does not control.

Official sources

  1. License: MIT
  2. MyIntervals/PHP-CSS-Parser on GitHub
  3. Project website
  4. README
  5. Releases
Add this badge to your README

If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.

Add this badge to your README

markdown
[![Hysen Labs](https://hysenlabs.com/badge/myintervals-php-css-parser.svg)](https://hysenlabs.com/projects/myintervals-php-css-parser)

Star history chart for your README

markdown
[![Star history](https://hysenlabs.com/chart/myintervals-php-css-parser.svg)](https://hysenlabs.com/projects/myintervals-php-css-parser)

Was this useful?