php html to plain text
How To Convert HTML Code To Plain Text With PHP
HTML is, of course, a very useful language, but sometimes, within a website, it can be problematic. Especially if you’re using a script to parse the text within it. In this article, converting or parsing HTML code into plain text variables will be explored.
Let’s see the example HTML that will be parsed into plain text –
HTML
Now let’s see it inside a PHP variable.
Finally, before we start, the output what we require, as plain text.
This is a body of text encapsulated in HTML. Let’s parse it
Method One
See the following examples of strip_tags() in use, the first using only the HTML string parameter and the second with the allowable tags parameter.
Example 1
Output
Example 2
Output
In these 2 examples, the strip_tags() function proves to be very swift to execute, check out the documentation on the function below.
Also, here is the above code in a PHP Fiddle to play with,
Method 2
There is a specially made class-based library purely dedicated to converting HTML markup into plain text output. It’s called html2text which is a very descriptive package name, to say the least. It has a public and free to use license which is available to download from it’s GitHub repository.
Example 1
Firstly, you will need to install this package from its repository page here. The quickest way is to use composer to download and install the package with the following command –
composer require html2text/html2text
If you haven’t got Composer yet and would like to start using it, then following this tutorial on using Composer.
The class can then be called within your PHP script as an object and be utilized with an object-oriented style of coding. Here is an example of it being used –
Output
Example 2
If you’re not a fan of Composer and like to do things the old school way, then you can simply download the class itself from the GitHub page. The Html2Text.php file is located within the ‘src’ directory within the repository. After downloading, place it in your classes folder and require it with PHP like the following.
Output
Summary
I can imagine you are quite surprised how easy it is to convert HTML to tag-less text. It’s super-simple and can be done with clean and understandable code. This is another one of the joys of using PHP, in some other languages, this simple task can be unnecessarily time-consuming. Happy Coding!
Преобразование HTML в обычный текст на PHP для электронной почты
кто-нибудь использует подобное подход к преобразованию HTML в обычный текст в PHP? И если да: вы рекомендуете какие-либо сторонние классы, которые я могу использовать? Или как лучше всего решить эту проблему?
14 ответов:
использовать html2text (например, HTML до текст), под лицензией Eclipse Public License. Он использует методы DOM PHP для загрузки из HTML, а затем повторяет полученный DOM для извлечения простого текста. Использование:
хотя и неполный, это с открытым исходным кодом и вклады приветствуются.
проблемы с другими конвертации скрипт:
преобразование из HTML в текст с помощью DOMDocument является жизнеспособным решением. Рассмотрим HTML2Text, который требует PHP5:
по поводу кодировки UTF-8, рецензия на «методические указания» государства-страницы:
собственная поддержка PHP для unicode довольно плоха, и она не всегда правильно обрабатывает utf-8. Хотя сценарий html2text использует безопасные для Юникода методы (без использования модуля mbstring), он не всегда справляется с собственной обработкой кодировок PHP. PHP на самом деле не понимает unicode или кодировки, такие как utf-8, и использует базовую кодировку системы, которая, как правило, является одной из семейства ISO-8859. В результате то, что может выглядеть для вас как допустимый символ в вашем текстовом редакторе, либо utf-8 или однобайтовый, вполне может быть неверно истолкован PHP. Поэтому, даже если вы думаете, что вы подаете действительный символ в html2text, вы вполне можете не быть.
автор предлагает несколько подходов к решению этой проблемы и утверждает, что версия 2 HTML2Text (с использованием DOMDocument) имеет поддержку UTF-8.
обратите внимание на ограничения для коммерческого использования.
для других вариантов функций дезинфекции см.:
HTML to plain text (for email)
Do you know any good HTML to plain text conversion class written in PHP?
I need it for converting HTML mail body to plain text mail body.
I wrote simple function, but I need more features like converting tables, adding links at the end, converting nested lists…
7 Answers 7
I’d suggest using a HTML to Markdown converter.
A particular mail sending implementation around here simply spawns lynx with the HTML and uses its output for the text version. It’s not perfect but works. You might also use links or elinks.
Using lynx is an option only if you have permission to run executables on the server. Doing so, however, is not considered a good practice. Furthermore, in secure hosts the php process is limited to be unable to spawn bash sessions, which are required for running lynx.
The most complete solution written entirely in PHP I was able to find is the Horde_Text_Filter_Html2text class. It is a part from the Horde framework.
Other solutions I’ve tried include:
If someone got the perfect solution, please, post it back for further reference!
As the question is about PHP and I found Dharmesh Hadiyal’s c# code quite useful, I have converted it to PHP.
(can’t comment, not enough reputation)
Not the answer you’re looking for? Browse other questions tagged php html text or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Converting HTML to plain text in PHP for e-mail
I use TinyMCE to allow minimal formatting of text within my site. From the HTML that’s produced, I’d like to convert it to plain text for e-mail. I’ve been using a class called html2text, but it’s really lacking in UTF-8 support, among other things. I do, however, like that it maps certain HTML tags to plain text formatting — like putting underscores around text that previously had tags in the HTML.
Does anyone use a similar approach to converting HTML to plain text in PHP? And if so: Do you recommend any third-party classes that I can use? Or how do you best tackle this issue?
14 Answers 14
Use html2text (example HTML to text), licensed under the Eclipse Public License. It uses PHP’s DOM methods to load from HTML, and then iterates over the resulting DOM to extract plain text. Usage:
Although incomplete, it is open source and contributions are welcome.
Issues with other conversion scripts:
here is another solution:
For other variations of sanitization functions, see:
Converting from HTML to text using a DOMDocument is a viable solution. Consider HTML2Text, which requires PHP5:
Regarding UTF-8, the write-up on the «howto» page states:
PHP’s own support for unicode is quite poor, and it does not always handle utf-8 correctly. Although the html2text script uses unicode-safe methods (without needing the mbstring module), it cannot always cope with PHP’s own handling of encodings. PHP does not really understand unicode or encodings like utf-8, and uses the base encoding of the system, which tends to be one of the ISO-8859 family. As a result, what may look to you like a valid character in your text editor, in either utf-8 or single-byte, may well be misinterpreted by PHP. So even though you think you are feeding a valid character into html2text, you may well not be.
The author provides several approaches to solving this and states that version 2 of HTML2Text (using DOMDocument) has UTF-8 support.
Преобразование HTML в обычный текст на PHP для электронной почты
кто-нибудь использует аналогичный подход к преобразованию HTML в обычный текст в PHP? И если да, то рекомендуете ли вы какие-либо сторонние классы, которые я могу использовать? Или как лучше всего решить эту проблему?
14 ответов
использовать html2text (например,HTML-код to текст), под лицензией Публичная Лицензия Eclipse. Он использует методы DOM PHP для загрузки из HTML, а затем перебирает полученный DOM для извлечения обычного текста. Использование:
хотя и неполный, он является открытым исходным кодом, и взносы приветствуются.
проблемы с другими конвертации скрипт:
преобразование из HTML в текст с помощью DOMDocument является жизнеспособным решением. Рассмотрим HTML2Text, для которого требуется PHP5:
Что касается UTF-8, запись на странице «howto» гласит:
собственная поддержка PHP для unicode довольно плоха, и она не всегда правильно обрабатывает utf-8. Хотя скрипт html2text использует unicode-безопасные методы (без использования модуля mbstring), он не всегда справляется с собственной обработкой кодировок PHP. PHP действительно не понимает unicode или кодировки, такие как utf-8, и использует базовую кодировку системы, которая, как правило, является одним из семейства ISO-8859. В результате, что может выглядеть для вас как допустимый символ в текстовом редакторе, В либо utf-8 или однобайтовый, вполне может быть неправильно истолкован PHP. Поэтому, даже если вы думаете, что вводите допустимый символ в html2text, вы вполне можете не быть.
автор предлагает несколько подходов к решению этой проблемы и заявляет, что версия 2 HTML2Text (с использованием DOMDocument) имеет поддержку UTF-8.
обратите внимание на ограничения для коммерческого использования.