I believe you can use Xpath, something like:
// Inicia o DOMDocument
$html = new DOMDocument();
// Importa o HTML (do $ingrediente)
$html->loadHTML($ingredientes);
// Inicia o XPath e busca por <ul>
$els = (new DOMXpath($html))->query("//ul");
// Obtém o HTML de cada <ul> e exibe entre <textarea>
foreach ($els as $el) {
echo "<textarea>" . $el->ownerDocument->saveHTML($el) . "</textarea>";
}
This will return:
<textarea><ul>
<li>100g de farinha de trigo</li>
<li>1 ovo</li>
<li>2 pitadas de sal</li>
<li>1 fio de azeite</li>
</ul>
</textarea>
<textarea><ul>
<li>Tomate</li>
<li>Cebola</li>
</ul></textarea>
In this case I’ve considered that you want to take everything in <ul>
. If you want to ignore the h2
I think you can use another Xpath, or the bad one you can use a *
and check on foreach
if he’s a h2
and ignore it.
With the comment, you can just pick up all the ul
and h2
and change the display based on what it is.
$html = new DOMDocument();
$html->loadHTML($ingredientes);
foreach ((new DOMXpath($html))->query('//ul|//h2') as $el) {
if(strtolower($el->nodeName) === 'ul') {
printf('<textarea>%s</textarea>', trim($el->ownerDocument->saveHTML($el)));
}else{
printf('<input value="%s">', htmlentities($el->textContent, ENT_HTML5 | ENT_QUOTES, 'utf-8'));
}
}
If he goes ul
it will display the HTML inside the <textarea>
, if he is a input
it will show the contents of h2
as a value. The $el->ownerDocument->saveHTML($el)
will return the HTML, already the $el->textContent
returns only the text.
Remember that this may still be vulnerable to an XSS!
Upshot:
<textarea><ul>
<li>100g de farinha de trigo</li>
<li>1 ovo</li>
<li>2 pitadas de sal</li>
<li>1 fio de azeite</li>
</ul>
</textarea>
<input value="Molho">
<textarea><ul>
<li>Tomate</li>
<li>Cebola</li>
</ul></textarea>
Test here.
opa, just need to return the title in the input tbm
– Leandro Marzullo
@Leandromarzullo I edited
– Inkeliz