1

The string has a html content.

For example:

<ul> 
  <li>....</li>
  <li>....</li> 
  <li>....</li> 
</ul>

Is there any function in php that can convert a string to an array like this

array(
  [0] => '<ul>',
  [1] => '<li>....</li>',
  [2] => '<li>....</li>',
  [3] => '</ul>'
)

can any one guide me.

Yoshi
  • 54,081
  • 14
  • 89
  • 103
Sudan Hari
  • 51
  • 2
  • 9

5 Answers5

0
$a='<ul> 
<li>....</li>
<li>....</li> 
<li>....</li> 
</ul>';


$as = explode("\n", $a);
print_r($as);

then

Array
(
    [0] => <ul> 
    [1] => <li>....</li>
    [2] => <li>....</li> 
    [3] => <li>....</li> 
    [4] => </ul>
)
JOE LEE
  • 1,058
  • 1
  • 6
  • 6
0

$str is your original string.

$array = explode("\n", $str);
Fabien
  • 12,486
  • 9
  • 44
  • 62
0

It depends on what you're actually trying to do.

If you're actually trying to separate the string by lines, its fairly easy:

$array = explode("\n", $htmlString);
foreach ($array as $key => $value) {
    $array[$key] = trim($value);
}

print_r($array); // Use this to dump out the value of $array.

However, if you're trying to parse the HTML in a meaningful way, then it's not so easy. You'll want to use DOMDocument or a dedicated HTML/XML parser instead.

For the reason why, read this:

RegEx match open tags except XHTML self-contained tags

Community
  • 1
  • 1
Stegrex
  • 4,004
  • 1
  • 17
  • 19
0

You can use SimpleXML for parse the HTML and later convert it to array

$result = (array) simplexml_load_string($htmlDocument);

http://www.php.net/manual/en/function.simplexml-load-string.php

$ul = <<<HTML
<ul> 
  <li>....</li>
  <li>....</li> 
  <li>....</li> 
</ul>
HTML;

$result = (array) simplexml_load_string($ul);

print_r($result);
Maks3w
  • 6,014
  • 6
  • 37
  • 42
0

i think you need a html praser for generic solution

try the links http://code.google.com/p/php-html2array/

to download the class file http://code.google.com/p/php-html2array/downloads/detail?name=class.htmlParser%20v1.02.zip&can=2&q=