【问题标题】:Using DomDocument to involve a element with another element?使用 DomDocument 将一个元素与另一个元素相关联?
【发布时间】:2016-10-25 20:24:23
【问题描述】:

我在名为results_all 的父 div 中有树 div,如下所示:

<div id="results_all">

<div class="result_information">
</div>

<div class="result_information">
</div>

<div class="result_information">
</div>

</div>

我想要做的就是涉及所有类名为result_information的div,使用以下代码&lt;tr&gt;&lt;th&gt;。

这样最终的结果是:

<tr><th>
<div class="result_information">
</div>
</th></tr>

<tr><th>
<div class="result_information">
</div>
</th></tr>

<tr><th>
<div class="result_information">
</div>
</th></tr>

如何使用 DomDocument 和 PHP 来做这种事情?

【问题讨论】:

  • PHP 不与 DOM 交互。你是用 javascript 做这个客户端,还是用 PHP 渲染 HTML 服务器端?
  • 我在 PHP 中的一个变量中有那个 HTML,我在做其他事情之前使用了类 domdocument。但是这种事情我不知道怎么解决……
  • 基本上是个骗子:stackoverflow.com/questions/3524431/…

标签: php dom domdocument


【解决方案1】:

这将使用 DOMXPath 匹配类,然后在循环结果时输出带有适当标签的匹配内容。

$html = '<div id="results_all">

<div class="result_information">
test3
</div>

<div class="result_information">
test2
</div>

<div class="result_information">
test
</div>

</div>
';

$classname = 'result_information';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$results = $xpath->query("//*[contains(@class, '$classname')]");


for($i = 0; $i < $results->length; $i++ ){
  print '<tr><th><div class="result_information">' . $results->item($i)->nodeValue . '</div></tr></th>';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2013-03-25
    • 1970-01-01
    相关资源
    最近更新 更多