Reputation: 331
I'm looking for a way to convert a HTML definition list <dl>
into a nested array with PHP.
Example list:
<dl>
<dt>A</dt>
<dd>A1</dd>
<dt>B</dt>
<dd>B1</dd>
<dd>B2</dd>
</dl>
Preferred output:
[ 'A' => ['A1'], 'B' => ['B1', 'B2'] ]
I already found a jQuery solution (Turning HTML <dl> into a nested JavaScript array with jQuery) which works (almost) like I want it to be BUT I'm working on a jQuery-less project and would therefor like to do the same with just PHP.
I've also already looked at PHP functions like XML_PARSE_INTO_STRUCT but unfortunately I don't get to a working solution with it.
So I'm currently stuck with my search. Can anyone give me a pointer into the right direction?
Upvotes: -2
Views: 291
Reputation: 161
You can simple do it using pure JS without using jQuery.
function dlToObject(dl){
if(!dl){
return {};
}
var elems = dl.querySelectorAll('dl dt, dl dd'),
parent = '',
result = {};
for(var i=0; i<elems.length; i++){
var element = elems[i];
if(element.tagName.toLowerCase() == 'dt'){
parent = element.innerText;
result[parent] = [];
}else{
result[parent].push(element.innerText)
}
}
return result;
}
var myDl = document.querySelector('dl');
console.log(dlToObject(myDl)); //{'A':['A1'],'B':['B1', 'B2']}
Upvotes: 0