S
S
Svoboo2022-02-10 17:12:09
PHP
Svoboo, 2022-02-10 17:12:09

How to convert html to formatted text in php?

There is text in html markup with paragraphs, lists, and so on. How can php convert it to plain formatted text for saving as txt?
For example, there is a type:

<p>абзац 1</p>
<p>абзац 2</p>
<ul>
  <li>пункт 1</li>
  <li>пункт 2</li>
  <li>пункт 3</li>
</ul>

You need to make it look like:
paragraph 1
paragraph 2
- paragraph 1 - paragraph
2 - paragraph
3

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2022-02-10
@Svoboo

So?

$txt = str_replace('<li', '-<li', $txt); // добавим минусы в списке
$txt = strip_tags($txt); // уберем теги

$rows = explode("\n", $txt); // разобьем на строки
$rows = array_map('trim', $rows); // уберем пробелы в начале и конце
$rows = array_filter($rows); // уберем пустые строки

echo implode("\n", $rows);  // склеим строки снова в текст

There are also ready-made libraries, such as this
https://github.com/soundasleep/html2text

R
Romi, 2022-02-10
@romicohen

Usually they use this: https://www.php.net/manual/ru/book.pcre.php - welcome to Hell =)
But personally, I would look for some kind of library on Github - there are probably many such packages.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question