Magento2 How can I convert html ul li list that I got from CMS block into Json or array format?
Can someone please guide me on that?
Try Like this :
$string = '<ul><li>Coffee</li><li>Tea</li><li>Milk</li></ul>';
$dom = new \DOMDocument;
$dom->loadHTML($string);
$array = [];
foreach($dom->getElementsByTagName('li') as $node) {
$array[] = $node->textContent;
}
echo "<pre>";print_r($array);
Results :
Array
(
[0] => Coffee
[1] => Tea
[2] => Milk
)
You can use php dom document
$string = '
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
';
$dom = new DOMDocument;
$dom->loadHTML($string);
foreach($dom->getElementsByTagName('li') as $node)
{
$array[] = $dom->saveHTML($node);
}
print_r($array);
Try This Code
<?php
$string = '
<ul>
<li>Coffee 0</li>
<li>Tea 0</li>
<li>Milk 0</li>
</ul>
<ul>
<li>Coffee 1</li>
<li>Tea 1</li>
<li>Milk 1</li>
</ul>
';
function tag_contents($string, $tag_open, $tag_close){
foreach (explode($tag_open, $string) as $key => $value) {
if(strpos($value, $tag_close) !== FALSE){
$result[] = substr($value, 0, strpos($value, $tag_close));;
}
}
return $result;
}
echo "<pre>";
$ulExtractData = tag_contents($string, '<ul>', '</ul>');
foreach ($ulExtractData as $ulExtractKey => $ulExtractVal) {
echo "*** UL Data ".$ulExtractKey." ***<br/>";
echo "<br/>Array Data :- <br/>";
print_r(tag_contents($ulExtractVal, '<li>', '</li>'));
echo "<br/>Json Data :- <br/>";
print_r(json_encode(tag_contents($ulExtractVal, '<li>', '</li>')));
echo "<br/>";
echo "<br/>";
}
echo "</pre>";