A powerful Python tool for converting CSS files and URLs into PHP arrays with advanced parsing and merging capabilities.
- 🎯 New: Split Selectors Mode - Optional splitting of combined CSS selectors
- 🔄 Convert CSS files/URLs to PHP arrays
- 📱 Handle media queries & pseudo-classes
- 🛠️ Auto-fix PHP syntax issues
- 📊 Detailed statistics & reporting
- 🔄 Advanced file merging with priority
- 💾 Customizable output paths
# Clone repository
git clone https://github.com/sakibweb/css2php
# Navigate to directory
cd css2php
# Install dependencies
pip install -r requirements.txt
Convert CSS files/URLs to PHP arrays
A versatile command-line tool to convert CSS stylesheets (from local files or URLs) into PHP arrays. Ideal for integrating CSS styles directly into your PHP applications, especially for dynamic styling or frameworks that utilize PHP-based styling.
- Advanced CSS Parsing: Leverages
cssutils
for robust parsing of CSS, handling complex stylesheets, including media queries and pseudo-classes. - Command-Line Interface (CLI): Easy to use via the terminal, making it perfect for automation and integration into build processes.
- Comprehensive Reporting: Provides detailed statistics on the conversion process, including input/output sizes, processing time, class counts, and syntax validation results.
- Error Handling: Includes options to skip errors and continue processing or to halt on errors for strict validation.
- File Overwrite Control: Option to prevent overwriting existing output files, ensuring data safety.
- Flexible Input Sources: Accepts both local CSS file paths and remote CSS URLs as input.
- Merge Functionality: Capable of merging multiple PHP array files (generated by CSS2PHP) into a single, consolidated file, useful for combining styles from different sources.
- Output Customization: Allows setting a custom output directory and filename prefix for generated PHP files.
- PHP Syntax Validation & Auto-Fix: Validates the generated PHP array for syntax errors and attempts to automatically fix common issues, ensuring code correctness.
- Split Selectors Mode: Option to split combined CSS selectors into individual keys in the PHP array. This might be useful in some scenarios but could lead to loss of CSS specificity. Controlled by the
--split-selectors
flag. - Statistics (Detailed): Generates in-depth processing statistics, including class counts, compression ratio, media query and pseudo-class detection, and syntax validation status.
- Tailwind CSS Compatibility: Handles common Tailwind CSS escape patterns in class names for cleaner PHP output.
- Timeout Control: Sets a timeout for fetching remote CSS files, preventing indefinite hangs.
- Version Information: Displays version details and author information.
-
Prerequisites:
- Python 3.6 or higher
pip
(Python package installer)php
(for syntax validation - ensure it's in your system's PATH)
-
Clone the repository and run it directly:
git clone https://github.com/sakibweb/css2php.git cd css2php pip install -r requirements.txt # Install dependencies
Basic conversion of a CSS file to a PHP array:
css2php styles.css
This will create a PHP file named styles.php
in the ./output
directory (if it exists, otherwise it will be created). The PHP file will contain a PHP array representation of the CSS styles.
Converting multiple CSS files:
css2php style1.css style2.css theme.css
Converting a CSS URL:
css2php https://example.com/styles.css
Specifying output directory and filename prefix:
css2php styles.css -o php_styles -n my_prefix_
This will save the output to php_styles/my_prefix_styles.php
.
Merging existing PHP array files:
css2php -m -md ./php_output -mn combined_styles
This will merge all PHP files found in the ./php_output
directory and create a merged file named combined_styles.php
in the ./output
directory.
Splitting CSS Selectors:
To split combined CSS selectors (like .class1.class2
) into individual keys:
css2php styles.css --split-selectors
Here is a list of all available command-line arguments, sorted alphabetically:
-
-i
,--info
:- Description: Show detailed statistics and information after processing each CSS source.
- Example:
css2php styles.css -i
-
-m
,--merge
:- Description: Enables the merge functionality to combine existing PHP array files.
- Example:
css2php -m -md ./php_output -mn combined_styles
-
-md
,--merge-dir
MERGE_DIR
:- Description: Specifies the directory containing PHP files to merge. Defaults to
./output
. - Example:
css2php -m -md ./custom_php_dir -mn merged_styles
- Description: Specifies the directory containing PHP files to merge. Defaults to
-
-mn
,--merge-name
MERGE_NAME
:- Description: Sets the filename prefix for the merged output file. Defaults to
main
. - Example:
css2php -m -md ./php_output -mn all_themes
- Description: Sets the filename prefix for the merged output file. Defaults to
-
-mo
,--merge-output
MERGE_OUTPUT
:- Description: Specifies the output directory for the merged PHP file. Defaults to
./output
. - Example:
css2php -m -md ./php_output -mo ./merged_output -mn merged_styles
- Description: Specifies the output directory for the merged PHP file. Defaults to
-
-n
,--name-prefix
NAME_PREFIX
:- Description: Sets a prefix for the output filename. Useful for organizing output files.
- Example:
css2php styles.css -n theme_
(Output:output/theme_styles.php
)
-
-o
,--output
OUTPUT_DIR
:- Description: Specifies the output directory for the generated PHP files. Defaults to
./output
. - Example:
css2php styles.css -o php_arrays
(Output:php_arrays/styles.php
)
- Description: Specifies the output directory for the generated PHP files. Defaults to
-
-p
,--priority-file
PRIORITY_FILE
:- Description: When merging, this option allows you to specify a priority PHP file. If duplicate classes are found, the properties from the priority file will take precedence.
- Example:
css2php -m -md ./php_output -p priority_styles.php -mn merged_styles
-
-r
,--no-overwrite
:- Description: Prevents overwriting existing output files. If an output file already exists, the conversion will be skipped, and an error will be raised.
- Example:
css2php styles.css -r
-
-s
,--skip-errors
:- Description: Instructs CSS2PHP to skip errors encountered during CSS fetching or parsing and continue processing other sources. Warnings will be printed for skipped errors.
- Example:
css2php styles.css -s
-
--split-selectors
:- Description: Splits combined CSS selectors into individual keys in the PHP array.
- Example:
css2php styles.css --split-selectors
-
-sources
[SOURCES ...]
:- Description: One or more CSS file paths or URLs to convert. This is the primary input for the tool.
- Example:
css2php styles.css https://example.com/theme.css
-
-t
,--timeout
TIMEOUT
:- Description: Sets the timeout in seconds for fetching remote CSS files. Defaults to 30 seconds.
- Example:
css2php https://slow-server.com/styles.css -t 60
-
-v
,--version
:- Description: Displays the current version of CSS2PHP, author information, and the repository link.
- Example:
css2php -v
The merge functionality allows you to combine multiple PHP files (previously generated by CSS2PHP) into a single, consolidated PHP array. This is particularly useful when:
- You have styles split across multiple files (e.g., component-based styles).
- You want to combine styles from different themes or modules.
Key aspects of merging:
- Property-Level Merging: When merging, CSS2PHP performs property-level merging. If the same CSS class exists in multiple input files, the tool will attempt to combine all unique CSS properties for that class into the merged output.
- "Last File Wins" Conflict Resolution: In case of property conflicts (i.e., the same CSS property is defined with different values in multiple input files for the same class), the property value from the last processed file will take precedence. The processing order is determined by file size (largest to smallest by default), with an option to prioritize a specific file using
--priority-file
. - Duplicate Class Detection: The merge process detects duplicate CSS class names across input files and reports them in the header comment of the merged output file.
- Priority File: Using the
--priority-file
option, you can designate a specific PHP file to have priority during merging. If a class is found in the priority file and other files, the properties from the priority file's class will be favored in case of conflicts.
CSS2PHP provides detailed reports and statistics for each conversion and merge operation. This information is included as a header comment in the generated PHP files.
For single CSS file conversion, the report includes:
- Source Information: File path or URL of the processed CSS.
- Processing Statistics (A-Z):
- Classes found
- Compression ratio (Output size / Input size)
- Input size (bytes)
- Media queries count
- Output size (bytes)
- Processing time (seconds)
- Pseudo-classes count
- Syntax validation status (Valid/Invalid)
- Configuration:
- Parse mode (Advanced -
cssutils
) - Skip errors (Yes/No)
- Timeout (seconds)
- Overwrite enabled (Yes/No)
- Split Selectors (Yes/No)
- Parse mode (Advanced -
- File Structure Explanation: Describes the structure of the generated PHP array.
For merge operations, the report includes:
- Merge Information:
- Source directory
- Files processed count
- Unique classes count in the merged output
- Duplicate classes found count
- Priority file (if used)
- Timestamp of generation
- Duplicate Information: Lists all duplicate CSS classes found during merging and the files where they were detected.
CSS2PHP validates the generated PHP array code for syntax errors using the php -l
command.
- Validation: After generating the PHP array, the tool runs a PHP syntax check.
- Auto-Fix: If syntax errors are detected, CSS2PHP attempts to automatically fix common issues, such as missing commas, extra commas, unescaped characters, and invalid media query keys.
- Error Reporting: If auto-fix is successful, a note is included in the output. If errors persist after auto-fix attempts, a warning message is displayed, and the tool will exit with an error code (unless
--skip-errors
is used).
Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests on the GitHub repository.
This project is licensed under the MIT License - see the LICENSE file for details.
Created by Sakibur Rahman (@sakibweb)