Thursday, 1 March 2018

PHP parse HTML tags





Possible Duplicate:
How to parse and process HTML with PHP?






I'm pretty new to PHP.
I have the text of a body tag of some page in a string variable.

I'd like to know if it contains some tag ... where the tag name tag1 is given, and if so, take only that tag from the string.
How can I do that simply in PHP?



Thanks!!


Answer



You would be looking at something like this:



$content = "";
$doc = new DOMDocument();

$doc->load("example.html");
$items = $doc->getElementsByTagName('tag1');
if(count($items) > 0) //Only if tag1 items are found
{
foreach ($items as $tag1)
{
// Do something with $tag1->nodeValue and save your modifications
$content .= $tag1->nodeValue;
}
}

else
{
$content = $doc->saveHTML();
}
echo $content;
?>


DomDocument represents an entire HTML or XML document; serves as the root of the document tree. So you will have a valid markup, and by finding elements By Tag Name you won't find comments.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...