# Using PHP to convert css to inline style



## IanArcher (Oct 24, 2011)

I am trying to write a php script that will take find the path of a webpage or a url, and convert the css from the server or local folder to inline code. I've looked pretty much all over the internet and looked for many solutions that could help me do this and done helped so far.

I have several 's in my page all linking to a css code called general.css
For e.g.


```
<div class="sys_main_logo" style="">
        
<div class="sys_ml">
            
<div class="sys_ml_wrapper">
```
I want it to be able to convert to the properties of the css it's linked to to inline code
for e.g.



```
<div style="position: relative; z-index: 56; background-color: #f4f4f4;>
```
Is this possible to write, can somebody assist me with this please? Thanks


----------



## ehymel (Aug 12, 2007)

There's probably a good reason you can't find how to do this... Why in the world would you want to?


----------



## Laxer (Aug 29, 2011)

First off, Welcome to TSG!
Secondly, Sorry for the rudeness above....

Now that we got the basics out of the way...

I would tackle this by using the php command: file_get_contents(); to get the contents of the webpage in text.

I would then do a series of find and replaces getting just the classes/ids of the elements on the page....

I would then explode these as an array and get just the div names and classes.

I would then do an other find and replace to remove old css and add in the inline elements....

In order to do this efficiently you will need to know REGEX...

there are a few tutorials online... Learn up


----------



## ehymel (Aug 12, 2007)

Nothing rude about my response, Laxer, it's a legitimate question. In your response you forgot to mention that to do this correctly he/she will have to properly cascade the styles to subelements, basically reproducing the entire DOM. This is not as simple as search/replace.

My question stands... why do this? Perhaps if we know what the goal of IanArcher we can provide better advice.


----------



## IanArcher (Oct 24, 2011)

Because i have to send a webpage in an e-mail, and not just a page/url, i would need the code that could do it every time i want to send a new page in an e-mail.

I found something thoug,

It's an Open type free use code for convert css to inline style codes by capturing from your own html code or a url and it outputs an html code when finished. Because i need to send webpages in an e-mail.

I am brand new to PHP so i wouldn't know where to start to use this code on my own separate from the page url below.

It's the source of this page

http://premailer.dialect.ca

Can someone shine some light on what do with the the below code to get the result i am seeking? Thanks.


```
<?php
/**
 * Premailer API PHP class
 * Premailer is a library/service for making HTML more palatable for various inept email clients, in particular GMail
 * Primary function is to convert style tags into equivalent inline styles so styling can survive <head> tag removal
 * Premailer is owned by Dialect Communications group
 * @link http://premailer.dialect.ca/api
 * @author Marcus Bointon <[email protected]>
 */
 
class Premailer {
    /**
     * The Premailer API URL
     */
    const ENDPOINT = 'http://premailer.dialect.ca/api/0.1/documents';

    /**
     * Central static method for submitting either an HTML string or a URL, optionally retrieving converted versions
     * @static
     * @throws Exception
     * @param string $html Raw HTML source
     * @param string $url URL of the source file
     * @param bool $fetchresult Whether to also fetch the converted output
     * @param string $adaptor Which document handler to use (hpricot (default) or nokigiri)
     * @param string $base_url Base URL for converting relative links
     * @param int $line_length Length of lines in the plain text version (default 65)
     * @param string $link_query_string Query string appended to links
     * @param bool $preserve_styles Whether to preserve any link rel=stylesheet and style elements
     * @param bool $remove_ids Remove IDs from the HTML document?
     * @param bool $remove_classes Remove classes from the HTML document?
     * @param bool $remove_comments Remove comments from the HTML document?
     * @return array Either a single strclass object containing the decoded JSON response, or a 3-element array containing result, html and plain parts if $fetchresult is set
     */
    protected static function convert($html = '', $url = 'http://test2.chamberhome.com/viewPage.php?ID=Newsletter_1', $fetchresult = true, $adaptor = 'hpricot', $base_url = '', $line_length = 65, $link_query_string = '', $preserve_styles = true, $remove_ids = false, $remove_classes = false, $remove_comments = false) {
        $params = array();
        if (!empty($html)) {
            $params['html'] = $html;
        } elseif (!empty($url)) {
            $params['url'] = $url;
        } else {
            throw new Exception('Must supply an html or url value');
        }
        if ($adaptor == 'hpricot' or $adaptor == 'nokigiri') {
            $params['adaptor'] = $adaptor;
        }
        if (!empty($base_url)) {
            $params['base_url'] = $base_url;
        }
        $params['line_length'] = (integer)$line_length;
        if (!empty($link_query_string)) {
            $params['link_query_string'] = $link_query_string;
        }
        $params['preserve_styles'] = ($preserve_styles?'true':'false');
        $params['remove_ids'] = ($remove_ids?'true':'false');
        $params['$remove_classes'] = ($remove_classes?'true':'false');
        $params['$remove_comments'] = ($remove_comments?'true':'false');
        $options = array(
            'timeout' => 15,
            'connecttimeout' => 15,
            'useragent' => 'PHP Premailer',
            'ssl' => array('verifypeer' => false, 'verifyhost' => false)
        );
        $h = new HttpRequest(self::ENDPOINT, HttpRequest::METH_POST, $options);
        $h->addPostFields($params);
        try {
            $response = $h->send();
            $result = json_decode($response->getBody());
            $code = $response->getResponseCode();
            if ($code != 201) {
                switch ($code) {
                    case 400:
                        throw new Exception('Content missing', 400);
                        break;
                    case 403:
                        throw new Exception('Access forbidden', 403);
                        break;
                    case 500:
                    default:
                        throw new Exception('Error', $code);
                }
            }
            $return = array('result' => $result);
            if ($fetchresult)() {
                //Get HTML and plain versions in parallel
                http_persistent_handles_clean();
                $pool = new HttpRequestPool;
                $pool->attach(new HttpRequest($result->documents->html, HttpRequest::METH_GET, $options));
                $pool->attach(new HttpRequest($result->documents->txt, HttpRequest::METH_GET, $options));
                $pool->send();
                foreach($pool as $request) {
                    if ($request->getUrl() == $result->documents->html) {
                        $return['html'] = $request->getResponseBody();
                    } elseif ($request->getUrl() == $result->documents->txt) {
                        $return['plain'] = $request->getResponseBody();
                    }
                }
                return $return;
            }
            return $result;
        } catch (HttpException $e) {
            var_dump($h, $e->getMessage());
            return false;
        }
    }

    /**
     * Central static method for submitting either an HTML string or a URL, optionally retrieving converted versions
     * @static
     * @throws Exception
     * @param string $html Raw HTML source
     * @param bool $fetchresult Whether to also fetch the converted output
     * @param string $adaptor Which document handler to use (hpricot (default) or nokigiri)
     * @param string $base_url Base URL for converting relative links
     * @param int $line_length Length of lines in the plain text version (default 65)
     * @param string $link_query_string Query string appended to links
     * @param bool $preserve_styles Whether to preserve any link rel=stylesheet and style elements
     * @param bool $remove_ids Remove IDs from the HTML document?
     * @param bool $remove_classes Remove classes from the HTML document?
     * @param bool $remove_comments Remove comments from the HTML document?
     * @return array Either a single element array containing the 'result' object, or three elements containing result, html and plain if $fetchresult is set
     */
    public static function html($html, $fetchresult = true, $adaptor = 'hpricot', $base_url = '', $line_length = 65, $link_query_string = '', $preserve_styles = true, $remove_ids = false, $remove_classes = false, $remove_comments = false) {
        return self::convert($html, '', $fetchresult, $adaptor, $base_url, $line_length, $link_query_string, $preserve_styles, $remove_ids, $remove_classes, $remove_comments);
    }

    /**
     * Central static method for submitting either an HTML string or a URL, optionally retrieving converted versions
     * @static
     * @throws Exception
     * @param string $url URL of the source file
     * @param bool $fetchresult Whether to also fetch the converted output
     * @param string $adaptor Which document handler to use (hpricot (default) or nokigiri)
     * @param string $base_url Base URL for converting relative links
     * @param int $line_length Length of lines in the plain text version (default 65)
     * @param string $link_query_string Query string appended to links
     * @param bool $preserve_styles Whether to preserve any link rel=stylesheet and style elements
     * @param bool $remove_ids Remove IDs from the HTML document?
     * @param bool $remove_classes Remove classes from the HTML document?
     * @param bool $remove_comments Remove comments from the HTML document?
     * @return array Either a single element array containing the 'result' object, or three elements containing result, html and plain if $fetchresult is set
     */
    public static function url($url, $fetchresult = true, $adaptor = 'hpricot', $base_url = '', $line_length = 65, $link_query_string = '', $preserve_styles = true, $remove_ids = false, $remove_classes = false, $remove_comments = false) {
        return self::convert('', $url, $fetchresult, $adaptor, $base_url, $line_length, $link_query_string, $preserve_styles, $remove_ids, $remove_classes, $remove_comments);
    }
}

/*
Simplest usage:
$pre = Premailer::html($var_with_some_html_in);
$html = $pre['html'];
$plain = $pre['plain'];
//Similarly for URLs:
$pre = Premailer::url($url);
*/
?>
```


----------

