0

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?

3 Answers 3

1

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
)
0

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);
3
  • Error: Class 'XYZ\TopHeaderMenuAPI\Model\DOMDocument' not found in
    – Arjun
    Feb 3, 2022 at 5:43
  • php-dom php-xml need to be enabled in your server Feb 3, 2022 at 5:52
  • installed them both still not working
    – Arjun
    Feb 3, 2022 at 9:42
0

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>";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.