V
V
Valentine52021-05-06 19:44:48
PHP
Valentine5, 2021-05-06 19:44:48

PHP: How to get parent, multiple children from html with XPath and keep their order in DOM tree?

Hello!

Parsing html and trying to parse it with XPath

$html = file_get_contents($url);

//echo $html;

$document = new DOMDocument();

$document->loadHTML($html);

$xpath = new DOMXpath($document);

$elements = $xpath->query('//div[contains(@class,"versions")]');

echo '<pre>';
print_r($elements['elements']);
echo '<pre>';


With this code, I am able to extract some elements of the parent tag, but I also need the children, with their order preserved and tied to dates. The original html has the following structure:
<div class='versions'>
<div>..</div>
<a class='versions-item'></a>
</div>


For some reason I can't open the versions-item from the received versions div. I do it like this:

$elements = $xpath->query('//div[contains(@class,"versions")]' and '//div [contains(@class,"versions-item")]');

But I don't even see the versions-item in the console..

Maybe someone had a similar problem? Tell me how to get both the parent and the necessary children with XPath while preserving the order (so that the dates do not lose their binding to links, the dates are in another div).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Sundukov, 2021-05-12
@Valentine5

One XPath request or how. We will have to write a couple of queries: 1) get //div[contains(@class,"versions")] a collection of div nodes that we make the context node for 2) query //a[contains(@class,"versions-item")].
The code would be something like this:

$elements = $xpath->query('//div[contains(@class,"versions")]');
foreach ($elements as $contextNode) {
    $versionsItemNode = $xpath->query('//a[contains(@class,"versions-item")]', $contextNode);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question