I used to do a bit of php programming years ago but I'm way out of practice so I wondered if I could get a bit of help?
I want to convert a html bulleted list into a multidimensional array. The bullet list contains 4 levels of indentation and will be sent to the function in text/string format (not a file). The html will only contain ol and li tags (e.g. no doctype, head, title etc.)
I figure this should be an easy thing to do but when I search I can only find array to html list rather than html list to array.
Any help appreciated.
Cheers, Dan.
My Answer:
Sure, I can help you with that. Here's a PHP function that will convert an HTML bulleted list into a multidimensional array:
php
function htmlListToArray($html) {
$dom = new DOMDocument();
$dom->loadHTML($html);
$listItems = $dom->getElementsByTagName('li');
$result = [];
$currentLevel = 0;
$currentPath = [];
foreach ($listItems as $item) {
$level = $item->parentNode->getAttribute('data-level');
$text = $item->nodeValue;
$path = array_slice($currentPath, 0, $level);
$currentPath[$level] = $text;
$parent = &$result;
foreach ($path as $key) {
$parent = &$parent[$key];
}
$parent[$text] = [];
}
return $result;
}
$html = '
- Item 1
- Subitem 1.1
- Subitem 1.2
- Item 2
- Subitem 2.1
- Subitem 2.2
- Subsubitem 2.2.1
';
$array = htmlListToArray($html);
print_r($array);
This function uses the DOMDocument class to parse the HTML and extract the list items. It then iterates over the list items, keeping track of the current level and path in the array. It builds the multidimensional array based on the indentation level of the list items.
You can test this function with the provided example HTML list. Let me know if you need any further assistance.
Rate this post
3 of 5 based on 2821 votesComments