Creating XML from an HTML List Using PHP

I would like to convert the list structure to html:

<ul> <li>Section 1</li> <li>Section 2 <ul> <li>Section 2.1</li> <li>Section 2.2</li> </ul> </li> <li>Section 3</li> </ul> 

In XML, like this:

 <sections> <section> <caption>Section 1</caption> <level>0</level> </section> <section> <caption>Section 2</caption> <level>0</level> </section> <section> <caption>Section 2.1</caption> <level>1</level> </section> <section> <caption>Section 2.2</caption> <level>1</level> </section> <section> <caption>Section 3</caption> <level>0</level> </section> </sections> 

I tried using PHP SimpleXML for reading in html, but it seems to have a problem when it encounters the <ul> tag inside the <li> .

Interestingly, someone can kindly suggest what is the easiest way to do this in PHP?

Many thanks to all of you.

+4
source share
1 answer

You can always simply parse this HTML in your XML structure. Something like that:

Suppose your HTML is located on a page called "sections.html". This is one way to do what you want to do:

 <?php # Create new DOM object $domOb = new DOMDocument(); # Grab your HTML file $html = $domOb->loadHTMLFile(sections.html); # Remove whitespace $domOb->preserveWhiteSpace = false; # Set the container tag $container = $domOb->getElementsByTagName('ul'); # Loop through UL values foreach ($container as $row) { # Grab all <li> $items = $row->getElementsByTagName('li'); # echo the values echo $items->item(0)->nodeValue.'<br />'; echo $items->item(1)->nodeValue.'<br />'; echo $items->item(2)->nodeValue; # You could write to your XML file, store in a string, anything here } ?> 

I have not tested this, but that is the general idea.

Hope this helps.

+3
source

Source: https://habr.com/ru/post/1338178/


All Articles