Skip to content
PHP Logo

How can text between <div> elements be extracted and saved in PHP?

To extract and save text between <div> elements in PHP, you can use the DOMDocument class to parse the HTML content and then use XPath to locate the <div> elements. Once you have located the desired <div> elements, you can extract the text content using the nodeValue property.

php
$html = '<div>This is some text</div><div>Another text</div>';

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

$xpath = new DOMXPath($dom);
$divs = $xpath->query('//div');

foreach ($divs as $div) {
    $text = $div->nodeValue;
    echo $text . PHP_EOL;
}