6个小时的研究,由于我正处于学习阶段,我无法弄清楚这一点,所以我决定在这个有帮助的社区找人
我有像remotesite.com/page1.html这样的远程页面,我们使用函数file_get_contents来获取它的源代码,然后在将其打印到我们的页面之前,我们使用DOMDocument来编辑这个源代码
$url = "remotesite.com/page1.html";
$html = file_get_contents($url);
$doc = new DOMDocument(); // create DOMDocument
libxml_use_internal_errors(true);
$doc->loadHTML($html); // load HTML you can add $html
//here we do some edits to remove or add contents
我想在打印之前将下面的Div添加到从远程站点获得的html代码中:
<div style="float: right; padding-right: 2px;"><a class="open_event_tab" target="_blank" href="some-hard-coded-text-here_'+content+'_title_'+lshtitle+'_event_'+id+'.html" >open event</a></div>
在搜索之后,我设法编写了创建div的函数,这是我的代码
function createDivNode($doc) {
$divNode = $doc->createElement('div');
$divNode->setAttribute('style', 'float: right; padding-right: 2px;');
$aNode = $doc->createElement('a', 'openEvent');
$aNode->setAttribute('class', 'open_event_tab');
$aNode->setAttribute('target', '_blank');
$aNode->setAttribute('href', 'some-hard-coded-text-here_'+content+'_title_'+lshtitle+'_event_'+id+'.html');
$divNode->appendChild($aNode);
return $divNode;
但现在我有两个问题:
1-href的软编码部分('+content+'_title_'+lshtitle+'_event_'+id+'
)不工作。
2-我不知道将div添加到我想要的位置
我想循环浏览从远程站点获得的html源代码,以获得每个看起来像下面的td,并在关闭td标签之前添加div
<td colspan="2">
<b>Video </b>
<span class="section">Sports</span><b>: </b>
<span id="category466" class="category">Motor Sports</span>
//here i want to add my div
</td>
广告1。看起来您错过了变量名中的$
,而且PHP中的串联是用.
而不是+
:完成的
$aNode->setAttribute('href', 'some-hard-coded-text-here_' . $content . '_title_' . $lshtitle . '_event_' . $id . '.html');
广告2。对于该查询,您可以构造一些匹配节点的xpath查询,然后只需$node->appendChild($divNode)
即可将其放入。