Last active
June 5, 2023 23:31
-
-
Save molotovbliss/18acc1522d3c23382757df2dbe6f0134 to your computer and use it in GitHub Desktop.
Convert html > ul > li to a PHP array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // original sauce: http://stackoverflow.com/a/9033361/158325 | |
| // dummy ul > li html content to parse into an array | |
| $html = "<ul> | |
| <li>Free shipping</li> | |
| <li>Equipment & speakesr</li> | |
| <li>Taxes & fees apply</li> | |
| </ul>"; | |
| // call function to convert | |
| print_r(ul_to_array($html)); | |
| // convert html > ul > li to a PHP array | |
| function ul_to_array ($ul) { | |
| if (is_string($ul)) { | |
| // encode ampersand appropiately to avoid parsing warnings | |
| $ul=preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $ul); | |
| if (!$ul = simplexml_load_string($ul)) { | |
| trigger_error("Syntax error in UL/LI structure"); | |
| return FALSE; | |
| } | |
| return ul_to_array($ul); | |
| } else if (is_object($ul)) { | |
| $output = array(); | |
| foreach ($ul->li as $li) { | |
| $output[] = (isset($li->ul)) ? ul_to_array($li->ul) : (string) $li; | |
| } | |
| return $output; | |
| } else return FALSE; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment