使用PHP时的多个属性的问题简单的HTML DOM [英] Problems with multiple attributes while using PHP Simple HTML DOM
问题描述
我使用此代码获取左侧导航栏的元素:
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)
,那么我得到 ALL 元素数据属性 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元素都使用regexp更改为具有适当数据属性的DIV元素,因为此解析器错误地计数这些元素的数量。
推荐答案
REGEX不是操作HTML ,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...
}
}
a href =http://stackoverflow.com/a/12752443/1519058> h0tw1r3 ):
OR (courtesy to h0tw1r3):
// array containing all the filtered nodes
$dts = array_filter($html->find('div.level2'), function($node){return $node->{'data-type'} == 'dt';});
请阅读 MANUAL 了解更多详情...
Please read the MANUAL for more details...
这篇关于使用PHP时的多个属性的问题简单的HTML DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!