How to add text node in new created element with PHP DOMDocument - php

How can I add content to the newly created tag? For example, I need to create like the following tag:
<script src="https://stackoverflow.com/">
alert("ok");
</script>
I have implemented the following code:
$finalDom = new DOMDocument;
$finalDom->loadHTML("", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$newElement = $finalDom->createElement("script");
$newElement->setAttribute("src", "https://stackoverflow.com/");
$finalDom->appendChild($newElement);
The result of this code is an only empty script tag:
<script src="https://stackoverflow.com/"></script>

You can set the content using $textContent property of DOMElement.
$newElement = $finalDom->createElement("script");
$newElement->setAttribute("src", "https://stackoverflow.com/");
$newElement->textContent = 'alert("ok");';

you can use createTextNode to add text node for the element, as
....
$newElement->setAttribute("src", "https://stackoverflow.com/");
$finalDom->appendChild($newElement);
$newElement->appendChild($finalDom->createTextNode('your text here'));
....

You can use any of these three options for adding text
elem.append(document.createTextNode(text))
elem.innerHTML = text
elem.textContent = text

Related

appendXML stripping out img element

I need to insert an image with a div element in the middle of an article. The page is generated using PHP from a CRM. I have a routine to count the characters for all the paragraph tags, and insert the HTML after the paragraph that has the 120th character. I am using appendXML and it works, until I try to insert an image element.
When I put the <img> element in, it is stripped out. I understand it is looking for XML, however, I am closing the <img> tag which I understood would help.
Is there a way to use appendXML and not strip out the img elements?
$mcustomHTML = "<div style="position:relative; overflow:hidden;"><img src="https://s3.amazonaws.com/a.example.com/image.png" alt="No image" /></img></div>";
$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="utf-8" ?>' . $content);
// read all <p> tags and count the text until reach character 120
// then add the custom html into current node
$pTags = $doc->getElementsByTagName('p');
foreach($pTags as $tag) {
$characterCounter += strlen($tag->nodeValue);
if($characterCounter > 120) {
// this is the desired node, so put html code here
$template = $doc->createDocumentFragment();
$template->appendXML($mcustomHTML);
$tag->appendChild($template);
break;
}
}
return $doc->saveHTML();
This should work for you. It uses a temporary DOM document to convert the HTML string that you have into something workable. Then we import the contents of the temporary document into the main one. Once it's imported we can simply append it like any other node.
<?php
$mcustomHTML = '<div style="position:relative; overflow:hidden;"><img src="https://s3.amazonaws.com/a.example.com/image.png" alt="No image" /></div>';
$customDoc = new DOMDocument();
$customDoc->loadHTML($mcustomHTML, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$doc = new DOMDocument();
$doc->loadHTML($content);
$customImport = $doc->importNode($customDoc->documentElement, true);
// read all <p> tags and count the text until reach character 120
// then add the custom html into current node
$pTags = $doc->getElementsByTagName('p');
foreach($pTags as $tag) {
$characterCounter += strlen($tag->nodeValue);
if($characterCounter > 120) {
// this is the desired node, so put html code here
$tag->appendChild($customImport);
break;
}
}
return $doc->saveHTML();

How to get data or value from any div in php

i Have create php page where use many div with different id name.
so i want to get data or value from one div.
Here am showing one div with id name
i want to get data or value from this div.
<div id="tablename">tablename</div>
i have use this but its not working.
$doc = new DomDocument();
$thediv = $doc->getElementById('tablename');
echo $thediv->textContent;
So please tell me how can i get this value from my div?
You need to pass the whole content of your page to the class, otherwise, it can't select nothing since it thinks the document is empty:
$content = '<div id="tablename"></div>';
$doc = new DomDocument();
$doc->loadHTML($content); // That's the addition
$thediv = $doc->getElementById('tablename');
echo $thediv->textContent;
More info:
loadHTML(): Load the HTML from a string.
loadHTMLFile(): Load the HTML from a file.
Downloaded and include PHP Simple HTML DOM Parser from https://sourceforge.net/projects/simplehtmldom/files/ and
Try this
include 'simple_html_dom.php';
$html = file_get_html("http://www.facebook.com");
$displaybody = $html->find('div[id=blueBarDOMInspector]', 0)->plaintext;
echo $displaybody ;exit;

how to give some words in html a link

I have this html as just example
this is some html code, and this is html
this is image <img src="any url with html word" alt="html" />
<iframe src="html"></iframe>
<script type="text/javascript">
var html = "any thing here";
var x = "this is html"
</script>
I want any way to replace all html word with html
As we see it may be in html tag attribute and we must exclude all these chance to replace and just replace this word if it plain text in span or p or div
I tried all dom ways to do that and no way
$dom = new DOMDocument();
$dom->loadHTML($str);
$xpath = new DOMXPath($dom);
$query_entries = $xpath->evaluate("(//div | //span | //p)[not(ancestor::a)]/text()");
foreach($query_entries as $element){
if($element instanceof DOMText){
$element->nodeValue = str_replace('html','html',$element->nodeValue);
}
}
When I replace the nodeValue with a html it escape it and if I try to decode it it make errors in js codes
Any regex solution?

How to use DOMDocument insertBefore

I have a div and I'm trying to insert a couple elements (h3 and p) into the div ahead of the existing h3 and p elements already living inside the div. The PHP documentation for insertBefore (http://www.php.net/manual/en/domnode.insertbefore.php) says this is exactly what should happen, but instead of inserting ahead of the existing elements, its replacing all existing elements inside my 'content' div.
Here's my code:
$webpage = new DOMDocument();
$webpage->loadHTMLFile("news.html");
$headerelement = $webpage->createElement('h3', $posttitle);
$pelement = $webpage->createElement('p', $bodytext);
$webpage->formatOutput = true;
$webpage->getElementById('content')->insertBefore($headerelement);
$webpage->getElementById('content')->insertBefore($pelement);
$webpage->saveHTMLFile("newpost.html");
I'm sure I'm just not understanding something... any help would be appreciated, thanks.
It's because you're not specifying a reference node that the inserted node should be inserted before. Think of it like this:
$whatTheElementIsInsertedInto->insertBefore($theElement, $whatItIsInsertedBefore)
Live demo (click).
$dom = new DOMDocument();
$dom->loadHtml('
<html><head></head>
<body>
<div id="content">
<h3>Original h3</h3>
</div>
</body>
</html>
');
//find the "content" div
$content = $dom->getElementById('content');
//find the first h3 tag in "content"
$origH3 = $content->getElementsByTagName('h3')->item(0);
//create a new h3
$newH3 = $dom->createElement('h3', 'new h3!');
//insert the new h3 before the original h3 of "content"
$content->insertBefore($newH3, $origH3);
echo $dom->saveHTML();

Adding style tags to head with PHP DOMDocument

I want to create and add a set of <style> tags to the head tags of an HTML document.
I know I can start out like this:
$url_contents = file_get_contents('http://example.com');
$dom = new DOMDocument;
$dom->loadHTML($url_contents);
$new_elm = $dom->createElement('style', 'css goes here');
$elm_type_attr = $dom->createAttribute('type');
$elm_type_attr->value = 'text/css';
$new_elm->appendChild($elm_type_attr);
Now, I also know that I can add the new style tags to the HTML like this:
$dom->appendChild($ss_elm);
$dom->saveHTML();
However, this would create the following scenario:
<html>
<!--Lots of HTML here-->
</html><style type="text/css">css goes here</style>
The above is essentially pointless; the CSS is not parsed and just sits there.
I found this solution online (obviously didn't work):
$head = $dom->getElementsByTagName('head');
$head->appendChild($new_elm);
$dom->saveHTML();
Thanks for the help!!
EDIT:
Is it possible?
getElementsByTagName returns an array of nodes, so probably try
$head->[0]->appendChild($new_elm);
$head = $dom->getElementsByTagName('head');
Return a DOMNodeList. I think it will be better to get the first element like this
$head = $dom->getElementsByTagName('head')->item(0);
So $head will be a DOMNode object. So you can use the appendChild method.
This is the solution that worked for me
// Create new <style> tag containing given CSS
$new_elm = $dom->createElement('style', 'css goes here');
$new_elm->setAttribute('type', 'text/css');
// Inject the new <style> Tag in the document head
$head = $dom->getElementsByTagName('head')->item(0);
$head->appendChild($new_elm);
You can also add this line at the end to have a clean indentation
// Add a line break between </style> and </head> (optional)
$head->insertBefore($dom->createTextNode("\n"));

Categories