Trying to replace contents of a Div, with no luck - php

Ive tried to use the Dom model with no bloody luck, getElementByID just doesnt work for me.
I loathe to resort to a regex but not sure what else to do.
The idea is to replace a <div id="content_div"> all sorts </div> with a new <div id="content_div"> NEW ALL SORTS HERE </div> and keep anything that was before or after it in the string.
The string is a partial HTML string and more specifically out of the wordpress Posts DB.
Any ideas?
UPDATE: I tagged this question PHP but probably should of mentioned Im looking for a PHP solution only.
Update: Code Example
$content = ($wpdb->get_var( "SELECT `post_content` FROM $wpdb->posts WHERE ID = {$article[post_id]}" ));
$doc = new DOMDocument();
$doc->validateOnParse = true;
$doc->loadHTMLFile($content);
$element = $doc->getElementById('div_to_edit');
So Ive tried a whole lot of code and this is what Ive got so far, probably not right but Ive been hacking at it for a little while now.

You're right: getElementByID doesn't work.
Try getElementById() instead. Javascript is case sensitive.

ok i assume $content is a snippet? then this may be all you need:
$doc = new DOMDocument();
$doc->validateOnParse = true;
$doc->loadHTMLFile('<html><body>' . $content . '</body></html>');
$element = $doc->getElementById('div_to_edit');

remember that you must have a valid webpage and that means full HTML tree:
<html>
<head>
<script type="text/javascript">
function changeText(div){
document.getElementById(div).innerHTML = 'my new text';
}
</script>
</head>
<body>
--- your body ---
<div id="DIV_ID">old text</div>
<input type="button" onclick="chageText('DIV_ID');" value="Click me" />
</body>
</html>
remember that you have to call getElementById with:
<script type="text/javascript"> // as from HTML5 you can use only <script>
document.getElementById("DIV_ID").innerHTML = 'my new text';
</script>

Try this..
var myDiv = document.getElementById('content_div');
myDiv.innerHTML = "NEW ALL SORTS HERE";

Related

PHP give tag id of its contents

I have a variable which consists of diffrent html tags:
$html = '<h1>Title</h1><u>Header</u><h2>Sub Title</h2><p>content</p><u>Footer</u>'
I want to find all the u tags in the $html variable and give them the id of their contents.
It should return:
$html = '<h1>Title</h1><u id="header" >Header</u><h2>Sub Title</h2><p>content</p><u id="footer" >Footer</u>'
You can use preg_replace() if you want it fast way, or learn about DOMDocument if you want to do it the proper way.
$pattern = '~<u>([^<]*)</u>~Ui';
$replace = '<u id="$1">$1</u>';
$html = preg_replace($pattern, $replace, $html);
You can use preg_replace.
$html = preg_replace('~<u>([^<]+)</u>~e','"<u id=\"".strtolower("$1")."\" >$1</u>"', $html);
The e means "evaluate", which allows you to cram the "strtolower" command into the replacement.
it will be good to do it using jquery if it suits your need else Forien answer is good to go
here it goes to do it in jquery
your html
<div id='specialString'>
<h1>Title</h1><u>Header</u><h2>Sub Title</h2><p>content</p><u>Footer</u>
</div>
your js
<script type="text/javascript">
$('#specialString > ul').each(function() {
$(this).attr('id', $(this).text());
});
</script>

How to select Content of ALL div's with PHP

I want to select contents of every DIV tags in PHP.
Just imagine we have this HTML page :
<html>
<body>
<div class="one">Content1</div>
<span>blah..</span>
<div class="two">Content2</div>
</body>
</html>
Now , i want to have every DIV tag content, For example from that HTML code , I want to have Content1 in One variable and the Content2 in the other Variable and so on ....
Just need to access the parts easily. Just this.
Every page have random number of DIV tags, so i need a flexable Code to detect DIV tags and put the content of every one in array or any type of variable..
How to do it ?
DOMDocument
$divs = array();
$HTML = '<html>
<body>
<div class="one">Content1</div>
<span>blah..</span>
<div class="two">Content2</div>
</body>
</html>';
$doc = new DOMDocument();
$doc->loadHTML($HTML);
foreach($doc->getElementsByTagName('div') as $div) {
array_push($divs, $div->textContent);
}
var_dump($divs);
example
try to use strip_tags() function:
http://php.net/manual/en/function.strip-tags.php
You can download PHP Simple HTML DOM Parser
And access the div tags like this :
$html = file_get_html('urltopage.com');
foreach($html->find('div') as $e)
echo $e->innertext . '<br>';

How to code PHP function that displays a specific div from external file if div called by getElementById has no value?

Thank you for answering my question so quickly. I did some more digging and ultimately found a solution for grabbing data from external file and specific div and posting it into another document using PHP DOMDocument. Now I'm looking to improve the code by adding an if condition that will grab data from a different div if the one called for initially by getElementById has now data. Here is the code for what I got so far.
External html as source.
<div id="tab1_header" class="cushycms"><h2>Meeting - 12:00pm to 3:00pm</h2></div>
My PHP file calling from source looks like this.
<?php
$source = "user_data.htm";
$dom = new DOMDocument();
$dom->loadHTMLFile($source);
$dom->preserveWhiteSpace = false;
$tab1_header = $dom->getElementById('tab1_header');
?>
<html>
<head>
<title></title>
</head>
<body>
<div><h2><?php echo $tab1_header->nodeValue; ?></h2></div>
</body>
</html>
The following function will output a message if a div id can't be found but...
if(!tab1_header)
{
die("Element not found");
}
I would like to call for a different div if the one called for initially has no data. Meaning if <div id="tab1_header"></div> then grab <div id="alternate"><img src="filler.png" /></div>. Can someone help me modify the function above to achieve this result.
Thanks.
either split up master.php so div1\2 are in a file each or set them each to a var, them include master.php, and use the appropriate variable
master.php
$d1='<div id="description1">Some Text</div>';
$d2='<div id="description2">Some Text</div>';
description1.php
include 'master.php';
echo $d1;
You can't do this solely with PHP includes unless you put the divs into separate files. Look into PHP templating; it's probably the best solution for this. Or, since you're new to the language, try using variables:
master.php
$description1 = '<div id="description1">Some Text</div>';
$description2 = '<div id="description2">Some Text</div>';
board1.php
include 'master.php';
echo $description1;
board2.php
include 'master.php';
echo $description2;
Alternatively, you could use JavaScript, but that might get a little messy.
Short answer is: although it's possible it's probably very bad idea taking this approach.
Longer answer: the solution may turn out to be too complicated. If in your master.php file is only HTML markup, you could read content of that file with file_get_contents() function and then parse it (i.e. with DOMDocument library functions). You would have to look for a div with given id.
$doc = new DOMDocument();
$doc->loadHTMLFile($file);
$divs = $doc->getElementsByTagName('div');
foreach ($divs as $div)
{
if( $div->getAttribute('id') == 'description1' )
{
echo $div->nodeValue."\n";
}
}
?>
If your master.php file has also some dynamic content you could do following trick:
<?php
ob_start();
include('master.php');
$sMasterPhpContent = ob_get_clean();
// same as above - parse HTML
?>
Edit:
$tab_header = $dom->getElementById('tab1_header') ? $dom->getElementById('tab1_header') : $dom->getElementById('tab2_header');

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"));

echo <body> doesn't activate jquery script

So I have a url from where I extract the data with extracthtml.php:
<?php
include("simple_html_dom.php");
$html = file_get_html($url);
$body = $html->find('body', 0);
$title = $html->find('title', 0);
echo $title;
echo $body;
?>
<script src="extract.js" type="text/javascript"></script>
Then with jquery I put a box around all the p elements to see if this communication works (test, am going to add more css manipulation later). My jquery starts with:
$(document).ready(function(){
$('p').css("border", "2px solid black");
});
Im guessing document.ready is the problem, because there appears to be no boxes around the p elements.
The issue is that you are echoing the jquery line to the browser after you close the page.
Since you echo the $body first, I would guess your page ends up looking something like this:
<body>
...
</body>
<script>
jquery here
</script>
Without seeing your page output this is only a guess, but if it is correct the browser will not run any code after the </body> tag. I would advise checking the source of your output to see if this is the case.

Categories