我怎样才能在php中获得div内容

时间:2022-03-14 10:14:32

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

我在php(字符串)中有一个div,我想获取内容。

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.

风格正在改变,我只知道div id。

UPDATED

更新

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

这是我的代码,与turbod源相同,结果也一样。

so this is the original html

所以这是原始的html

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

And after this code I get the following: link

在这段代码之后,我得到以下内容:链接

3 个解决方案

#1


16  

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

使用php DomDocument类。 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"]');

#2


1  

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

要保存XML / HTML片段,需要保存每个子节点:

$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          
"

#3


-1  

Isn't it enough to do...

做不够......

$id->nodeValue

#1


16  

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

使用php DomDocument类。 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"]');

#2


1  

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

要保存XML / HTML片段,需要保存每个子节点:

$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          
"

#3


-1  

Isn't it enough to do...

做不够......

$id->nodeValue