我有以下函数可以在 a 中查找值HTML DOM
;
它可以工作,但是当我给出以下参数时$value
:Levi's Baby Overall,
它会破裂,因为它不会逃脱 , 和 ' 字符
如何从 DOM XPath 查询中转义所有无效字符?
private function extract($file,$url,$value) {
$result = array();
$i = 0;
$dom = new DOMDocument();
@$dom->loadHTMLFile($file);
//use DOMXpath to navigate the html with the DOM
$dom_xpath = new DOMXpath($dom);
$elements = $dom_xpath->query("//*[text()[contains(., '" . $value . "')]]");
if (!is_null($elements)) {
foreach ($elements as $element) {
$nodes = $element->childNodes;
foreach ($nodes as $node) {
if (($node->nodeValue != null) && ($node->nodeValue === $value)) {
$xpath = preg_replace("/\/text\(\)/", "", $node->getNodePath());
$result[$i]['url'] = $url;
$result[$i]['value'] = $node->nodeValue;
$result[$i]['xpath'] = $xpath;
$i++;
}
}
}
}
return $result;
}