-2

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?

4
  • Could read in the HTML file using file_get_contents, then use preg_match to grab everything from dl to /dl, use that and build from there Commented Jun 4, 2018 at 15:05
  • Then use vanilla javascript! JQuery is not a seperate language, it is a javascript framework remember Commented Jun 4, 2018 at 15:09
  • @clearshot66 I'm using the PHP Simple HTML DOM script to extract my source so I've the <dl> to </dl> code already isolated. Commented Jun 4, 2018 at 21:05
  • @RiggsFolly yeah you're 100% right, native Javascript is indeed an option too! So funny how I always overlook that... guess it must be because I'm not overly into Javascript. Commented Jun 4, 2018 at 21:05

1 Answer 1

0

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']}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, works great! That said I'm currently also looking into a pure PHP solution found at stackoverflow.com/questions/12803228/… as a PHP solution still holds my preference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.