Answer the question
In order to leave comments, you need to log in
How to implement a recursive traversal of store categories?
Hello, the task is to parse data from a remote site.
There is a page with categories of the 1st level, when you click on a category, you get to a page with categories of the 2nd level and so on.
in theory, the nesting is something like this
Балкон и сад
Грили
Зонты
Балконные экраны
Зонты от солнца и основания для зонтов
Шатры и тенты
Шатры
Тенты
Кашпо и растения для сада
Растения
Шпаллеры
Ванная
...
$result = [
[
'name' => 'Грили',
'link' => 'url/url/url/',
'dirs' => [
[
'name' => 'Грили декоративные',
'link' => 'url/url/url/',
'dirs' => []
],
[
'name' => 'Грили латунные',
'link' => 'url/url/url/',
'dirs' => []
]
]
],
[...]
];
$result = [];
$topCats = getItemsCategory($document, $result); // передаю страницу с категориями верхнего уровня
function getItemsCategory(phpQueryObject $document, &$result)
{
$childrens = pq($document)->find('.range-catalog-list__link')->elements;
if ($childrens) { // есть потомки
foreach ($childrens as $item) {
$name = trim(pq($item)->find('.range-catalog-list__title')->text());
$link = trim(pq($item)->attr('href'));
if ($doc = phpQuery::newDocumentHTML(getSslPage($link)))
$arReturn[]['dirs'] = getItemsCategory($doc);
return [
'name' => $name,
'link' => $link,
];
}
} else { // нет потомков
return [];
}
}
Answer the question
In order to leave comments, you need to log in
Something like this you can try
$doc = new DOMDocument();
$doc->loadHTML($html);
$output = array();
showDOMNode($doc, $output );
function showDOMNode(DOMNode $domNode, $output) {
$i = 1;
foreach ($domNode->childNodes as $node)
{
$output[$i] = array('name'=>$node->nodeName, 'value'=> $node->nodeValue, 'dirs'=> array());
if($node->hasChildNodes()) {
showDOMNode($node, $output[$i]['dirs']);
}
$i++;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question