Manipulate HTML from php

I have an html file, index.phpI want to take the contents in <div>with the class of mainthis file and replace it with another text. How can i achieve this?

Sample content in html:

<div class="main">
Replace this text with some code!
</div>

I want to get the content in this div using php and replace it with other content. But I do not know how to do this.

Update: I know the client trick with javascript. I want to make this server side. And the file will be html, not php. so I think I need to open html in php and do it, although I don’t know exactly how to do it.

Can this be done using the xpath parser or html dom? A Google search gave me these terms, but I don’t know what they really are.

+5
source share
3 answers

For this you can use PHP DOM classes / functions.

Start by creating / loading a document:

$d = new DOMDocument();
$d->loadHTML($yourWellFormedHTMLString);

Then you will want to find the node document that you want to modify. You can do this with XPath:

$xpathsearch = new DOMXPath($d);
$nodes = $xpathsearch->query('//div[contains(@class,'main')]');  

Then you will need to iterate over the matching nodes and create new nodes inside:

foreach($nodes as $node) {
    $newnode = $d->createDocumentFragment();
    $newnode->appendXML($yourCodeYouWantToFillIn);
    $node->appendChild($newnode);
}

If you don't mind fiddling with the library at an early stage of development, check out CAST (Content-Address Style Templates). This is largely intended to do what you describe, and if nothing else, you could look inside the source to see examples.

(. , , //div[contains(@class,'main')] CSS div.main... . , , , , , xpath , . ids .:)

+14

:

$fileContents=file_get_contents($file_path);

http://php.net/manual/en/function.file-get-contents.php

div:

$newHtmlContent=preg_replace("/<div class=\"main\">(.*)</div>/i",'<div class="main">Some text here</div>',$fileContents);

http://php.net/manual/en/function.preg-replace.php

, : http://www.regular-expressions.info/tutorial.html

:

file_put_contents($file_path,$newHtmlContent);

http://www.php.net/manual/en/function.file-put-contents.php

, : http://simplehtmldom.sourceforge.net/ .

, , div - div...

+1

<div class="main">
<?php readfile ('path/to/some/file'); ?>
</div>

PHP

<div class="main">
<?php include ('path/to/some/file') ?>
</div>
+1

All Articles