PHP: Convert <ul> <li> Tree HTML tag to an array
Posted
by marknt15
on Stack Overflow
See other posts from Stack Overflow
or by marknt15
Published on 2010-05-12T08:53:56Z
Indexed on
2010/05/12
9:14 UTC
Read the original article
Hit count: 539
Hi,
I'm using jsTree and I need to convert this HTML tag tree code <ul> <li>
to a PHP array.
The jsTree HTML tag will be passed to PHP to be parsed and store in a structured tree PHP array(see below for the PHP array structure).
Additional question: Is my desired PHP array structure good or you can suggest a good structure? I'm open for suggestions.
Thanks in advance :)
Cheers, Mark
jsTree Screenshot:
HTML Tree String:
<ul class="ltr">
<li id="phtml_1" class=" open">
<a style="" class=" " href="#"><ins> </ins>Folder 1</a>
<ul>
<li class="leaf" id="phtml_2">
<a style="" class=" " href="#"><ins> </ins>Child 1.1</a>
</li>
<li class="open" id="phtml_3">
<a style="" class=" " href="#"><ins> </ins>Folder 1.1</a>
<ul>
<li class="leaf last" rel="default">
<a href="" style="" class=" "><ins> </ins>Child 1.1.1</a>
</li>
</ul>
</li>
<li class="last open" rel="default">
<a href="" style="" class=" "><ins> </ins>Folder 1.2</a>
<ul>
<li class="leaf" rel="default">
<a href="" style="" class=" "><ins> </ins>Child 1.2.1</a>
</li>
<li class="leaf last" rel="default">
<a href="" style="" class=" "><ins> </ins>Child 1.2.2</a>
</li>
</ul>
</li>
</ul>
</li>
<li id="phtml_5" class="file open">
<a style="" class=" " href="#"><ins> </ins>Folder 2</a>
<ul>
<li class="leaf" rel="default">
<a href="" style="" class=" "><ins> </ins>Child 2.1</a>
</li>
<li class="leaf last" rel="default">
<a href="" style="" class="clicked"><ins> </ins>Child 2.2</a>
</li>
</ul>
</li>
<li class="leaf last" rel="default">
<a href="" style="" class=" "><ins> </ins>Outer Child</a>
</li>
</ul>
PHP Array Structure:
<?php
$tree_array = array(
'Folder 1' => array(
'Child 1.1',
'Folder 1.1' => array(
'Child 1.1.1'
),
'Folder 1.2' => array(
'Child 1.2.1',
'Child 1.2.2'
),
),
'Folder 2' => array(
'Child 2.1',
'Child 2.2'
),
'Outer Child'
);
echo '<pre>',print_r($tree_array),'</pre>';
?>
PHP print_r Output:
Array
(
[Folder 1] => Array
(
[0] => Child 1.1
[Folder 1.1] => Array
(
[0] => Child 1.1.1
)
[Folder 1.2] => Array
(
[0] => Child 1.2.1
[1] => Child 1.2.2
)
)
[Folder 2] => Array
(
[0] => Child 2.1
[1] => Child 2.2
)
[0] => Outer Child
)
© Stack Overflow or respective owner