phpsymfonygoutte

Get raw HTML code of element with Symfony DomCrawler


Html structure:

   <div id="product">
     <p>some text</p>
     <p>some text2</p>
   </div>    

My PHP code:

$client = new Client();
$crawler = $client->request('GET', $url);
echo $crawler->filter('#product')->text();

returns:

some text some text2

But I need:

<p>some text</p>
<p>some text2</p>

Solution

  • Well, there is one but ugly way - via iterating over its nodes:

    $html = '';
    
    foreach ($crawler as $domElement) {
        $html.= $domElement->ownerDocument->saveHTML();
    }
    

    Or, in your case, you should iterate over filtered element:

    $html = '';     
    $product = $crawler->filter('#produkt');
     
    foreach ($product as $domElement) {
        foreach($domElement->childNodes as $node) {
            $html .= $domElement->ownerDocument->saveHTML($node);
        }
    }
    

    From documentation