PHP将HTML字符串拆分为数组 [英] PHP Split html string into array
问题描述
我希望我能从你们那里得到一些帮助。
I hope I can get some help from you guys.
这就是我正在努力解决的问题,
我有一串HTML,看起来像这样:
This is what I'm struggling with, I have a string of HTML that will look like this:
<h4>Some title here</h4>
<p>Lorem ipsum dolor</p>
(some other HTML here)
<h4>Some other title here</h4>
<p>Lorem ipsum dolor</p>
(some other HTML here)
我需要拆分所有< h4>
从其余内容开始,例如第一个< h4>
之后和第二个< h4>
需要与第一个< h4>
相关,例如:
I need to split all the <h4>
from the rest of the content, but for example the content after the first <h4>
and before the second <h4>
needs to be related to the first <h4>
, something like this:
Array {
[0] => <h4>Some title here</h4>
[1] => <p>Lorem ipsum dolor</p>
}
Array {
[0] => <h4>Some other title here</h4>
[1] => <p>Lorem ipsum dolor</p>
}
这是建造一架手风琴(很难解释为什么我在做这样,但必须是这种方式),< h4>
将成为手风琴面板的标题,并且在单击时将展开并显示与它们相关的内容
This is to build an accordion (quite difficult to explain why I'm doing this way, but it has to be this way), and the <h4>
will be the accordion panel headings and when clicked it will expand and show the content associated with them.
我希望我能明确说明我的问题,让我知道您的想法,以及如何更好地做到这一点。
I hope I made my problem clear, let me know of your thoughts and how should I do this the better way.
我一直在研究 DOMDocument
,但是我也尝试了 explode()
,但没有成功。
I was looking into DOMDocument
, but I also tried with explode()
but with no success.
我有使用JavaScript的方法,但是我需要用PHP实现相同的功能,但是使用DOM和PHP进行操作相当复杂。
I have this working with JavaScript but I need to achieve the same thing with PHP, but it's quite complicated to play with the DOM with PHP.
谢谢。
推荐答案
我能够按照<一个href = https://stackoverflow.com/questions/18156164/parse-html-and-get-all-h3s-after-an-h2-before-the-next-h2-using-php>示例 Derek S 给了我。
结果是:
$html_string = 'HTML string';
$dom = new DOMDocument();
$dom->loadHTML($html_string);
foreach($dom->getElementsByTagName('h4') as $node) {
$title = $dom->saveHTML($node);
$content[$title] = array();
while(($node = $node->nextSibling) && $node->nodeName !== 'h4') {
$content[$title] = $dom->saveHTML($node);
}
}
这会将标题保存在 $ title
以及 $ content [$ title]
中的对应内容。
This will save the titles inside $title
and the correspondent content inside $content[$title]
.
这篇关于PHP将HTML字符串拆分为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!