问题描述
我使用这段代码获取左侧导航栏的元素:
I use this code for getting elements of left navigation bar:
function parseInit($url) {
$ch = curl_init();
$timeout = 0;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$data = parseInit("https://www.smile-dental.de/index.php");
$data = preg_replace('/<(d[ldt])( |>)/smi', '<div data-type="$1"$2', $data);
$data = preg_replace('/<\/d[ldt]>/smi', '</div>', $data);
$html = new simple_html_dom();
$html = $html->load($data);
但面临这样的问题。
例如,如果我使用这样的语法获取元素: $ html-> find(div [data-type = dd] .level2)
,然后我得到全部元素数据属性 DT,DD,DL 和类名 LEVEL2 。如果我使用另一种语法: $ html-> find(div.level2 [data-type = dd])
,那么我得到 ALL 数据属性 DD 的元素,但类名称 LEVEL1,LEVEL2和LEVEL3等。
可以解释一下问题是什么?感谢提前!
But faced with such problem.
For example, if I use such syntax for getting elements: $html->find("div[data-type=dd].level2")
, then I get ALL elements with data attributes DT, DD, DL and class name LEVEL2. If I use another syntax: $html->find("div.level2[data-type=dd]")
, then I get ALL elements with data attribute DD, but with class names LEVEL1, LEVEL2 and LEVEL3 etc..Could you explain me what the problem is? Thanks in advance!
PS:所有DT,DL和DD元素都使用正则表达式更改为具有适当数据属性的DIV元素,因为此解析器不正确地计数
推荐答案
,DOM解析器是...而您使用的simple_html_dom可以轻松实现...
REGEXes are not made to manipulate HTML, DOM parsers are... And simple_html_dom you're using can do it easily...
以下代码将做你想要的(检查注释):
The following code will do what you want just fine (check comments):
$data = parseInit("https://www.smile-dental.de/index.php");
// Create a DOM object
$html = new simple_html_dom();
$html = $html->load($data);
// Find all tags to replace
$nodes = $html->find('td, dd, dl');
// Loop through every node and make the wanted changes
foreach ($nodes as $key => $node) {
// Get the original tag's name
$originalTag = $node->tag;
// Replace it with the new tag
$node->tag = 'div';
// Set a new attribute with the original tag's name
$node->{'data-type'} = $originalTag;
}
// Clear DOM variable
$html->clear();
unset($html);
现在,对于多个属性过滤,您可以使用以下方法之一:
Now, for multiple attributes filtering, you can use either of the following methods:
foreach ( $html->find("div.level2") as $key => $node) {
if ( $node->{'data-type'} == 'dt' ) {
# code...
}
}
或(礼貌地):
// array containing all the filtered nodes
$dts = array_filter($html->find('div.level2'), function($node){return $node->{'data-type'} == 'dt';});
请阅读了解更多详情...
Please read the for more details...
这篇关于使用PHP时使用多个属性的问题简单的HTML DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!