问题描述:

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.

网友答案:
$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>
)
网友答案:

$str is your original string.

$array = explode("\n", $str);
网友答案:

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

网友答案:

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);
网友答案:

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=

相关阅读:
Top