Skip to content Skip to sidebar Skip to footer

Loop Through

Tags Inside Html String From Database

I want to loop through tags inside HTML string that came from database. Example: $htmlString = '

1

2

3

'; I want to loop thro

Solution 1:

You should use DOMDocument instead, it'll help you parse HTML more easily, here is a sample code:

<?php$string = "<p>1</p><p>2</p>";
$domDocument = new DOMDocument();
$domDocument->loadHTML($string);
$paragraphElements = $domDocument->getElementsByTagName('p');
foreach ($paragraphElementsas$p) {

        var_dump($p->nodeValue);

}

Output:

string'1' (length=1)
string'2' (length=1)

Solution 2:

CODE:

<?php$dom_document = new DOMDocument();

$dom_document->loadHTML("<p>1</p><p>2</p><p>3</p>");

$p_tags = $dom_document->getELementsByTagName("p");

for($i=0;$i<$p_tags->length;++$i){
    echo$p_tags->item($i)->nodeValue,"<br/>";
}

Solution 3:

Why you use simple XML? There is HTML DOM Parser:

<?php$x = "<p>1</p><p>2</p>";
$html = str_get_html($x);
$html->find('p');
echo$html; // Outputs 1 and 2?>

Documentation: https://github.com/sunra/php-simple-html-dom-parser

Solution 4:

$x = "<p>1</p><p>2</p>";

$values = str_replace(array('<p>', '</p>'), ' ', $x);
$values = explode(' ', $values);

foreach ($valuesas$val){
    echo($val);
}

Post a Comment for "Loop Through

Tags Inside Html String From Database"