我有这个 HTML 模板:
<div>
<p class="ex-fr">Tex1 - Edit</p>
Out Text 1 Edit
<p>Tex2 - Edit</p>
Out Text 1 Edit
<br>
Out Text 3 Edit
</div>
我希望创建一个页面来编辑此模板的文本和标签属性。
为了实现这个目标,我需要将这个 HTML 解析成 PHP 数组并加载页面。
下面是一个假设的数组,可能是从上面的 HTML 中获取的:
$parsedHtml = array(
'thisIs'=>'tag',
'tag' => 'div',
'attr' => '',
'children'=> array(
0 => array(
'thisIs'=>'tag',
'tag' => 'p',
'attr' => 'class="ex-fr"',
'children'=> array(
'thisIs'=>'text',
'tag' => '',
'attr' => '',
'children'=> 'Tex1 - Edit'
)
),
1 => array(
'thisIs'=>'text',
'tag' => '',
'attr' => '',
'children'=> 'Out Text 1 Edit'
),
2 => array(
'thisIs'=>'tag',
'tag' => 'p',
'attr' => '',
'children'=> array(
'thisIs'=>'text',
'tag' => '',
'attr' => '',
'children'=> 'Tex2 - Edit'
)
),
3 => array(
'thisIs'=>'text',
'tag' => '',
'attr' => '',
'children'=> 'Out Text 2 Edit'
),
4 => array(
'thisIs'=>'sTag',
'tag' => 'br',
'attr' => '',
'children'=> ''
),
5 => array(
'thisIs'=>'text',
'tag' => '',
'attr' => '',
'children'=> 'Out Text 3 Edit'
)
)
);
目前我尝试使用这个类: https://code.google.com/p/php-html2array/downloads/detail?name=class.htmlParser.php 问题在于该类仅返回标签,而不应包含文本内容(如“Out Text 1 Edit”或“Out Text 2 Edit”)。
因此,给定的数组是:
(
[-{}-2-0-{}-] => Array
(
[id] => -{}-2-0-{}-
[father] =>
[tag] => div
[innerHTML] => <p class='ex-fr'>Tex1 - Edit</p> Out Text 1 Edit <p>Tex2 - Edit</p> Out Text 1 Edit <br> Out Text 3 Edit
[htmlText] => <div > <p class='ex-fr'>Tex1 - Edit</p> Out Text 1 Edit <p>Tex2 - Edit</p> Out Text 1 Edit <br> Out Text 3 Edit </div>
[stratr] =>
[childNodes] => Array
(
[0] => Array
(
[id] => -{}-1-0-{}-
[father] => -{}-2-0-{}-
[tag] => p
[innerHTML] => Tex1 - Edit
[htmlText] => <p class='ex-fr'>Tex1 - Edit</p>
[stratr] => class='ex-fr'
[childNodes] => Array
(
)
)
[1] => Array
(
[id] => -{}-1-1-{}-
[father] => -{}-2-0-{}-
[tag] => p
[innerHTML] => Tex2 - Edit
[htmlText] => <p>Tex2 - Edit</p>
[stratr] =>
[childNodes] => Array
(
)
)
[2] => Array
(
[id] => -{}-0-0-{}-
[father] => -{}-2-0-{}-
[tag] => br
[innerHTML] => <br>
[htmlText] => <br>
[stratr] =>
[childNodes] => Array
(
)
)
)
)
)
有没有将HTML解析为数组的方法? (我已经搜索了浏览器如何解析HTML代码并在控制台中显示它,比如Chrome或Firebug,并且它们允许编辑)
我知道使用正则表达式解析HTML很难或者不可能,还有其他的解决方法吗?
提前感谢大家,对我的糟糕英语表示歉意。
最好的问候,Andrea。
http://php.net/simplexml
吗?它可能无法给你想要的结果,但它是一个起点。 - Carlos Campderrós