won*_*ana 9 html php parsing dom
根据SIMPLE HTML DOM PARSER的文档(在"如何修改HTML元素"选项卡下),此代码查找第一个实例<div class="hello">:
$html = str_get_html('<div class="hello">Hello</div><div class="world">World</div>');
$html->find('div[class=hello]', 0)->innertext = 'foo';
echo $html; // Output: <div class="hello">foo</div><div class="world">World</div>
Run Code Online (Sandbox Code Playgroud)
如果我想插入"富"到最后的情况下<div class="hello">,假设HTML代码有很多实例<div class="hello">.
什么应该取代0?
好吧,从那以后
// Find all anchors, returns a array of element objects
$ret = $html->find('whatever');
Run Code Online (Sandbox Code Playgroud)
返回array保存所有<whatever>元素,您可以使用PHP的常规数组函数获取最后一个元素,例如end
$last = end($ret);
Run Code Online (Sandbox Code Playgroud)
如果SimpleHtmlDom完全实现了用于查询的CSS3选择器,您还可以修改要使用的查询
:last-of-type
Run Code Online (Sandbox Code Playgroud)
只找到返回的节点列表中的最后一个兄弟节点.
从手册:
// Find lastest anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', -1);
Run Code Online (Sandbox Code Playgroud)