-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?

golabs
  • 169
  • 1
  • 11
  • 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 – clearshot66 Jun 04 '18 at 15:05
  • Then use vanilla javascript! JQuery is not a seperate language, it is a javascript framework remember – RiggsFolly Jun 04 '18 at 15:09
  • @clearshot66 I'm using the PHP Simple HTML DOM script to extract my source so I've the
    to
    code already isolated.
    – golabs Jun 04 '18 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. – golabs Jun 04 '18 at 21:05

1 Answers1

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']}
Vitalii
  • 161
  • 1
  • 10
  • Thanks, works great! That said I'm currently also looking into a pure PHP solution found at https://stackoverflow.com/questions/12803228/simple-html-dom-how-get-dt-dd-elements-to-array as a PHP solution still holds my preference. – golabs Jun 04 '18 at 22:51