<h1 class="property-title">Title 1</h1>
<h1 class="property-title">Title 2</h1>
How would I get just the first h1 using the class name from the DOM that it placed in a string?
<h1 class="property-title">Title 1</h1>
<h1 class="property-title">Title 2</h1>
How would I get just the first h1 using the class name from the DOM that it placed in a string?
PHP’s inbuilt DOMDocument is useful for parsing HTML:
<?php
function getTextBetweenTags($htmlContent, $tagName)
{
$d = new DOMDocument();
$d->loadHTML($htmlContent);
$output = [];
foreach($d->getElementsByTagName($tagName) as $item){
$output[] = $item->textContent;
}
return $output;
}
$content = <<<EOT
<h1 class="property-title">Title 1</h1>
<h1 class="property-title">Title 2</h1>
EOT;
$h1Content = getTextBetweenTags($content, 'h1');
echo reset($h1Content), PHP_EOL;