Nishil Athikkal
Nishil Athikkal

Reputation: 79

Select Content of div using php

I have a div named "main" in my page. I put the code to convert a html into pdf using php at the end of page. I want to select the content (div named main contains paragraphs, charts, tables etc.).

How ?

Upvotes: 1

Views: 4764

Answers (3)

Moin Ahmed
Moin Ahmed

Reputation: 2898

Below code will show you how to get DIV tag's content using PHP code.

PHP Code:

  <?php
    $content="test.html";
    $source=new DOMdocument();
    $source->loadHTMLFile($content);
    $path=new DOMXpath($source);
    $dom=$path->query("*/div[@id='test']");
    if (!$dom==0) {
       foreach ($dom as $dom) {
          print "
    The Type of the element is: ". $dom->nodeName. "
    <b><pre><code>";
          $getContent = $dom->childNodes;
          foreach ($getContent as $attr) {
             print $attr->nodeValue. "</code></pre></b>";
          }
       }
    }
  ?>

We are getting DIV tag with ID "test", You can replace it with your desired one.

test.html

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

Output:

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

Upvotes: 2

user2470774
user2470774

Reputation: 11

You should put the php code into a separate file from the html and use something like DOMDocument to get the content from the div.

$dom = new DOMDocument();
$dom->loadHTMLFile('yourfile.html');
...

Upvotes: 1

aeno
aeno

Reputation: 560

You cannot directly interact with the HTML DOM via PHP. What you could do, is using a with an input containing your content. When submitting the form you can access the data via PHP.

But maybe you want to use Javascript for that task?

Nevertheless, a quick'n'dirty PHP example:

<form action="" method="post">
    <textarea name="content">hello world</textarea>
</form>

<?php
   if (isset($_POST['content'])) {
       echo $_POST['content'];
   }
?>

Upvotes: 0

Related Questions