I want to convert nested ul li to a PHP array.
The HTML code that I have is something looks like:
<ul id="main-menu">
<li id="firstNavItem"><a href="index.html">Home</li>
<li><a href="Warp.html">Warp</a>
<ul>
<li><a href="Warp-how-it-works.html">How it works</a>
</li>
<li><a href="Warp-Engine.html">Warp Engine</a>
</li>
<li><a href="WarpFactors.html">Warp Factors</a>
</li>
<li><a href="">Fuel</a>
<ul>
<li><a href="Anti-Matter.html">Anti-Matter</a>
</li>
<li><a href="Deuterium.html">Deuterium</a>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="Fact-or-Fiction.html">Fact or Fiction</li>
<li><a href="StarTrek.html">Star Trek</a>
<ul>
<li><a href="Enterprise.html">Enterprise</a>
</li>
<li><a href="Voyager.html">Voyager</a>
</li>
</ul>
</li>
<li><a href="about.html">About</a>
</li> </ul>
It must be converted to an array.
I tried several ways to parse, But I fail.
One of the ways that I've used is:
$doc = new \DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadHTML($data);
$i = 0;
while( is_object($finance = $doc->getElementsByTagName("li")->item($i)) )
{
foreach($finance->childNodes as $nodename)
{
if($nodename->nodeName == 'li')
{
foreach($nodename->childNodes as $subNodes)
{
$arr[$i] = $subNodes->nodeValue.PHP_EOL;
}
}
else
{
$s = explode(' ', $nodename->nodeValue);
if (count($s) == 1)
{
$arr[$i] =$nodename->nodeValue;
}
else
{
$arr[$i] = $s;
}
}
}
$i++;
}
<ul>and create an array for that. Then find the<li>children and make them elements of the array. Then if the element contains another<ul>, create a sub-array there and recurse.