Skip to content

Instantly share code, notes, and snippets.

@aflansburg
Created September 12, 2017 20:22
Show Gist options
  • Save aflansburg/384330911f10a320171c5972480e7d61 to your computer and use it in GitHub Desktop.
Save aflansburg/384330911f10a320171c5972480e7d61 to your computer and use it in GitHub Desktop.
Just playing with HTML parsing
<?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