Skip to content

Instantly share code, notes, and snippets.

@fjorgemota
Created September 16, 2012 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fjorgemota/3732851 to your computer and use it in GitHub Desktop.
Save fjorgemota/3732851 to your computer and use it in GitHub Desktop.
Convert HTML to Javascript using DOM in PHP
<?php
function convertHTMLtoJS($html){
if(is_string($html)){
$type = "string";
}
else{
$type = get_class($html);
}
switch($type){
case "DOMDocument":
case "DOMElement":
$id = $html->nodeName."_".md5(uniqid())."_element";
if($html->nodeName != "#document"){
$code = "var ".$id." = document.createElement('".$html->nodeName."');\n";
}
else{
$code = "";
}
if(!!$html->attributes){
foreach($html->attributes as $attr){
$code .= $id.".setAttribute('".$attr->name."', '".$attr->value."');\n";
}
}
if(!!$html->childNodes){
foreach($html->childNodes as $child){
if($child->nodeType == XML_TEXT_NODE){
$code .= $id.".appendChild(document.createTextNode('".htmlentities($child->nodeValue)."'));\n";
}
else{
$element = convertHTMLtoJS($child);
$code .= $element["code"];
if($html->nodeName != "#document"){
$code .= $id.".appendChild(".$element["id"].");\n";
}
else{
$id = $element["id"];
}
}
}
}
return array("code"=>$code, "id"=>$id);
break;
case "DOMDocumentType":
return array("code"=>"","id"=>"");
break;
default:
case "string":
$dom = new DOMDocument();
$dom->strictErrorChecking = FALSE;
$dom->loadHTML($html);
$result = convertHTMLtoJS($dom);
return $result;
break;
}
return NULL;
}
//$result = convertHTMLtoJS("<html><head><title>teste</title></head><body style='background:red;'>ola <span id='testando'>teste</span> do mundo</body></html>"); // gets a array with id of the first Child and the code of the rest..
//echo $result["code"]; // to show the code
// echo "document.body.appendChild(".$result["id"].")"; // To show the result in document.body
?>
@iraniamir
Copy link

ThX . man

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment