Search code examples
phpdomdomdocument

$dom = new DOMDocument; show one line


I'm doing a DOMDocument where i get information from a website, i'm trying to get the text inside of the <p> </p> , the code works fine but the fact is that the website has many <P> codes so i get all the information, i just want the information of the first <p>, the <p> has not id classes so it doesn't help please check the code and help me to know how to get only the first <p>

$html = file_get_contents('http://example.com');

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

$links = $dom->getElementsByTagName('p'); 

forsearch ($links as $link){  
echo $link->nodeValue; 
echo $link->getAttribute('') , '<br>'; 
$goal = $link->nodeValue;
}

the code works fine but it shows all the text, i just need the first <p> not all.


Solution

  • To get only the first paragraph element you can do it like that:

    $doc = new \DOMDocument();
    $doc->loadHTML(file_get_contents('http://example.com'));
    
    $paragraphs = $doc->getElementsByTagName('p');
    echo "Content of first paragraph: {$paragraphs->item(0)->nodeValue}\n";