我一直在寻找解决方案,但尚未找到正确的方法。
情况是这样的:
我需要找到给定类的页面上的所有链接(例如class="tracker"
),然后在末尾附加查询字符串值,因此当用户加载页面时,这些某些链接会使用一些动态信息进行更新。
我知道如何做到这一点JavaScript,但我真的很想调整它以运行服务器端。我很新PHP,不过从表面上看,XPath可能是我正在寻找的,但我还没有找到合适的例子来开始。有没有类似的东西GetElementByClass
?
任何帮助将不胜感激!
影子
有没有类似的东西GetElementByClass
?
这是我发起的一个实现......
function getElementsByClassName(DOMDocument $domNode, $className) {
$elements = $domNode->getElementsByTagName('*');
$matches = array();
foreach($elements as $element) {
if ( ! $element->hasAttribute('class')) {
continue;
}
$classes = preg_split('/\s+/', $element->getAttribute('class'));
if ( ! in_array($className, $classes)) {
continue;
}
$matches[] = $element;
}
return $matches;
}
该版本不依赖上面的辅助函数。
$str = '<body>
<a href="">a</a>
<a href="http://example.com" class="tracker">a</a>
<a href="http://example.com?hello" class="tracker">a</a>
<a href="">a</a>
</body>
';
$dom = new DOMDocument;
$dom->loadHTML($str);
$anchors = $dom->getElementsByTagName('body')->item(0)->getElementsByTagName('a');
foreach($anchors as $anchor) {
if ( ! $anchor->hasAttribute('class')) {
continue;
}
$classes = preg_split('/\s+/', $anchor->getAttribute('class'));
if ( ! in_array('tracker', $classes)) {
continue;
}
$href = $anchor->getAttribute('href');
$url = parse_url($href);
$attach = 'stackoverflow=true';
if (isset($url['query'])) {
$href .= '&' . $attach;
} else {
$href .= '?' . $attach;
}
$anchor->setAttribute('href', $href);
}
echo $dom->saveHTML();
Output
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<a href="">a</a>
<a href="http://example.com?stackoverflow=true" class="tracker">a</a>
<a href="http://example.com?hello&stackoverflow=true" class="tracker">a</a>
<a href="">a</a>
</body></html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)