Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End RSS Feed with Altered Images Reply To: RSS Feed with Altered Images

#167642
kingkool68
Participant

Oh DOMDocument(), you’re so silly! Here is a workaround for stripping out the automatically-added DOCTYPE gibberish from http://www.php.net/manual/en/domdocument.savehtml.php#88273

First we need to wrap our HTML fragment in a <div>

$content = '<div>' . $content . '</div>';

Then this line will essentially get the innerHTML of the first div…

$content = substr($doc-&gt;saveXML($doc-&gt;getElementsByTagName('div')-&gt;item(0)), 5, -6);   

I don’t know what is going on in the <description> element of the feed as my code doesn’t touch that part. I did notice in the regular RSS feed there is an extra closing </p> after the first sentence…

&lt;![CDATA[Stripes are pretty easy to do in CSS these days. <a href="https://css-tricks.com/css3-gradients/">CSS gradients</a> via the background-image property really got our back. I thought I'd document some variations in one easy to reference place.
</p>
Normal Colored Diagonal Stripes

Here is the full code to do what you want.

function css_tricks_custom_feeds() {
    add_feed( 'email', 'get_me_the_email_feed_template');
}
add_action( 'init', 'css_tricks_custom_feeds' );

function get_me_the_email_feed_template() {
    add_filter( 'the_content_feed', 'css_tricks_super_awesome_feed_image_magic' );
    include( ABSPATH . '/wp-includes/feed-rss2.php' );
}

function css_tricks_super_awesome_feed_image_magic( $content ) {
     //Weirdness we need to add to strip the doctype with later.
    $content = '<div>' . $content . '</div>';
    $doc = new DOMDocument();
    $doc-&gt;LoadHTML( $content );
    $images = $doc-&gt;getElementsByTagName('img');
    foreach ($images as $image) {
        $image-&gt;removeAttribute( 'height' );
        $image-&gt;setAttribute( 'width', '320' );
    }

    //Strip weird DOCTYPE that DOMDocument() adds in
    $content = substr($doc-&gt;saveXML($doc-&gt;getElementsByTagName('div')-&gt;item(0)), 5, -6);
    return $content;
}

And PHP Simple DOM is a great PHP class that lets you parse HTML using CSS selectors we all know and love. It makes scraping sites a pure delight. Didn’t need to get it involved for this task though as PHP’s built in DOMDocument() class does the job.