Convert HTML to Text in PHP

Do you want to convert HTML to Text in PHP? If yes, it is actually very easy. To convert Html to Text using PHP, it is necessary to remove Html tags.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Convert HTML to Text</title>
</head>
<body>
    <p>
        This is a body of text encapsulated in <b>HTML</b>.
        <b>Let's parse it</b>
    </p>
</body>
</html>
convert html to text using PHP

PHP Code to Convert HTML to Text

PHP “strip_tags()” function will strip tags from HTML, XML, and PHP. We are going to use “strip_tags()” function to convert HTML to Text.

PHP

$html = "
    <body>
        <p>
            This is a body of text encapsulated in <b>HTML</b>.
            <b>Let's parse it!</b>
        </p>
    </body>";

echo strip_tags($html);

The above code will strip all tags and output only text.

Output

This is a body of text encapsulated in HTML. Let's parse it!

If you don’t want to remove some tags for example “<b></b> tag then don’t worry! because “strip_tags()” has allowable tags option which means you can exclude some tags from stripping.

Read also:- Download Image from URL in PHP

PHP

$html = "
    <body>
        <p>
            This is a body of text encapsulated in <b>HTML</b>.
            <b>Let's parse it!</b>
        </p>
    </body>";

echo strip_tags($html, '<b>') // Don't strip <b> Tags

Output

This is a body of text encapsulated in <b>HTML</b>.
<b>Let's parse it!</b>

I recommend you guys to use the PHP inbuilt function “strip_tags()”. Don’t need to use third party libraries such as “html2text”.

Conclusion

I hope this article helps you to convert html to text easily with the help of PHP. If you have any doubts please comment down. We will help you. Share this article with other peoples to help them.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment