0

I'm trying to understand how I can save the html string found by query so that I can access it's elements.

I'm using the following query to find the below ul list.

$data = $xpath->query('//h2[contains(.,"Hurricane Data")]/following-sibling::ul/li');

<h2>Hurricane Data</h2>
<ul>
    <li><strong>12 items</strong> found, see <a href="/link">here</a>for more information</li>
    <li><strong>19 items</strong> found, see <a href="/link">here</a>for more information</li>
    <li><strong>13 items</strong> found, see <a href="/link">here</a>for more information</li>
</ul>

If I print_r($data), I get the following DOMNodeList Object ( [length] => 3 ) which refers to the 3 elements found.

If I foreach() into the $data I get a DOMElement Object with all 3 li data.

What I'm trying to accomplish is to put each li data into an accessible array, but I want to parse the html strong & a tags inside too.

Now, I've already did everything I want to do, except the strong and a tags aren't being inserted into the arrays, here is what I've come up with.

$string = [];
$query = $xpath->query('//h2[contains(.,"Hurricane Data")]/following-sibling::ul/li');
foreach($query as $values){
    $try = new \DOMDocument;
    $try->loadHTML(mb_convert_encoding($values->textContent, 'HTML-ENTITIES', 'UTF-8'));

    $string[] = $try->saveHTML();
}

echo $string[0];
// outputs = 12 items found, see here for more information
// no strong tags, no hyperlinks

1 Answer 1

2

You don't need to reprocess the data, you can just say to save this particular node...

foreach($query as $values){    
    $string[] = $doc->saveHTML($values);
}

Where $doc is the document used as the basis for your XPath query.

Sign up to request clarification or add additional context in comments.

1 Comment

I feel so lame Nigel. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.