Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a div content in php

Tags:

php

I have a div in php(string) and I want to get the content.

for example:

<div id="product_list" style="width:100%; float:none;">
      <div>
       bla bla bla
      </div>
      bla bla          
</div>

and I want

<div>
     bla bla bla
</div>
     bla bla

The style is changing, I know only the div id.

UPDATED

this is my code, same as turbod source and the results are the same too.

so this is the original html

$doc = new DOMDocument();
$doc->loadHTML($buffer);
$id = $doc->getElementById('product_list')

And after this code I get the following: link

like image 387
OHLÁLÁ Avatar asked Jun 27 '11 10:06

OHLÁLÁ


People also ask

Can you have div in PHP?

The HTML <div> tag is used for defining a section of your document. With the div tag, you can group large sections of HTML elements together and format them with CSS.

How do I set the content of a div?

Use the textContent property to change the text of a div element, e.g. div. textContent = 'Replacement text' . The textContent property will set the text of the div to the provided string, replacing any of the existing content.

Can you have a value in a div?

An <div> element can have any number of data-* attributes, each with their own name.

How to use the div tag?

The <div> tag defines a division or a section in an HTML document. The <div> tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript. The <div> tag is easily styled by using the class or id attribute. Any sort of content can be put inside the <div> tag!


2 Answers

Use the php DomDocument class. http://www.php.net/manual/en/class.domdocument.php

$dom = new DOMDocument();

$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$divContent = $xpath->query('//div[@id="product_list"]');
like image 68
turbod Avatar answered Nov 12 '22 01:11

turbod


To save an XML/HTML fragment, you need to save each child node:

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$result = '';
foreach($xpath->evaluate('//div[@id="product_list"]/node()') as $childNode) {
  $result .= $dom->saveHtml($childNode);
}
var_dump($result);

Output:

string(74) "
      <div>
       bla bla bla
      </div>
      bla bla          
"

If you only need the text content, you can fetch it directly:

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
var_dump(
  $xpath->evaluate('string(//div[@id="product_list"])')
);

Output:

string(63) "

       bla bla bla

      bla bla          
"
like image 38
ThW Avatar answered Nov 12 '22 01:11

ThW