Showing posts with label dom. Show all posts
Showing posts with label dom. Show all posts

Sunday, June 17, 2012

Getting Contents of a DIV With PHP's DOM

Hi! Almost all of us use XML in our web sites. We can get contents with parsing XML files. But sometimes, we need another ways. The reason of this is that we want to get only one dom's content. For example an img element's content or it's value of id

Well, I will introduce how to get contents of element in this article. That's why I'll show you the sample given belown.

For my example, I got two files here:
  1. GetContent.php
  2. test.html
$source=new DOMdocument();
$path=new DOMXpath($source);
if (!$dom==0) {
   foreach ($dom as $dom) {
      print "<br>The Type of the element is: ". $dom->nodeName. "<br><b><pre><code>";
      $getContent = $dom->childNodes;
      foreach ($getContent as $attr) {
         print $attr->nodeValue. "</code></pre></b>";
So, If you analyze the sample given above, you can see the point easily. The point is the content of div element which is id=test. The reason of existing test.html page is to get div's content.

<div id="test">This is my content</div>

What we have just seen up there, should be like on this demo page.

The Type of the element is: div
This is my content

The result is the text above. We'll see you guys next article!