Created
September 12, 2017 20:22
-
-
Save aflansburg/384330911f10a320171c5972480e7d61 to your computer and use it in GitHub Desktop.
Just playing with HTML parsing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$html = ' | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title><?=$title?></title> | |
</head> | |
<body> | |
<p id="thisP">Some stuff here to parse! ABCDEFGHIJKLMNOPQRSTUVWXYZ</p> | |
</body> | |
</html>'; | |
$dom_doc = new DOMDocument(); | |
$dom_doc->loadHtml($html); | |
$dom_xpath = new DOMXpath($dom_doc); | |
$message = "This is the message generated from the function"; | |
$updatedMsg = writeMsgToDoc($message, $dom_xpath); | |
function writeMsgToDoc($message, $dom_xpath){ | |
$els = $dom_xpath->query("*/p[@id = 'thisP']"); | |
foreach ($els as $el){ | |
//echo "\n[". $el->nodeName. "]"; | |
$nodes = $el->childNodes; | |
foreach ($nodes as $node){ | |
$newMessage = $node->nodeValue. "\n"; | |
return $newMessage; | |
} | |
} | |
} | |
?> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Title</title> | |
</head> | |
<body> | |
<p>Here's what was parsed:<?=$html?></p> | |
<p>Post-parse = <?=$updatedMsg?></p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment