How can I get a div content in php

后端 未结 3 698
难免孤独
难免孤独 2020-11-27 07:02

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

for example:

相关标签:
3条回答
  • 2020-11-27 07:32

    Isn't it enough to do...

    $id->nodeValue
    
    0 讨论(0)
  • 2020-11-27 07:46

    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"]');
    
    0 讨论(0)
  • 2020-11-27 07:52

    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          
    "
    
    0 讨论(0)
提交回复
热议问题