user1661677 user1661677 - 6 months ago 38
PHP Question

How to isolate a specific nested value in complex DOM element string?

I'm looking to return the value that is nested in the an element containing an href value with

john
in it (in this example, it is
7 goals
). Any help?

<?php
$html_string = '<div class="foo"><a href="../john-smith.html"><span>7 goals</span></a></div><div class="foo2"><h2><a href="../adam-green.html">8 points</a></h2></div>';
echo $isolated_character;

Answer

As a variant, you Can use class DomDocument and its Xpath

$d = new DomDocument();
$d->loadHTML($html_string);
$x = new DomXpath($d);
echo $res = $x->evaluate('string(//a[contains(@href, "john")]/span)'); // 7 goals
Comments