Reputation: 1748
I have a multilevel list, example below:
<ul>
<li>Test column 01
<ul>
<li>Test column 02
<ul>
<li>Test column 03
<ul>
<li>Test column 04
<ul>
<li>Test column 05</li>
<li>Test column 05</li>
<li>Test column 05</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
I would like to run some php code that outputs the list as a csv file, formatted like below:
Test column 01
,Test column 02
,,Test column 03
,,,Test column 04
,,,,Test column 05
,,,,Test column 05
,,,,Test column 05
Basically, I want to be able to run an html list, (with an unlimited amount of levels), through some php code, and output a csv file that can be opened in excel, preserving the list levels in columns.
If I could find some way of adding a class to each list item, depending on its level, so first level list items get a class of level1, second level, a class of level2 etc etc, then it should be fairly straightforward to find and replace the rest.
Any ideas/help greatly appreciated.
Upvotes: 3
Views: 4423
Reputation: 317137
This would work for your example HTML:
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('li') as $li) { // #1
printf(
'%s%s%s',
str_repeat(',', get_depth($li)), // #2
trim($li->childNodes->item(0)->nodeValue), // #3
PHP_EOL
);
}
function get_depth(DOMElement $element)
{
$depth = -1;
while ( // #4
$element->parentNode->tagName === 'li' ||
$element->parentNode->tagName === 'ul'
) {
if ($element->parentNode->tagName === 'ul') { // #5
$depth++;
}
$element = $element->parentNode;
}
return $depth;
}
You can see the demo here.
Explanation of the marks:
Upvotes: 3