我想检查<img>
标记是否有alt=""
文本,还需要找到DOM中img标记的行号。目前我已经编写了以下代码,但仍然找到了行号。
例如:
$doc = new DOMDocument();
$doc->loadHTMLFile('http://www.google.com');
$htmlElement = $doc->getElementsByTagName('html');
$tags = $doc->getElementsByTagName('img');
echo $tags->item(0)->getLineNo();
foreach ($tags as $image) {
// Get sizes of elements via width and height attributes
$alt = $image->getAttribute('alt');
if($alt == ""){
$src = $image->getAttribute('src');
echo "No alt text ";
echo '<img src="http://google.com/'.$src.'" alt=""/>'. '<br>';
}
else{
$src = $image->getAttribute('src');
echo '<img src="http://google.com/'.$src.'" alt=""/>'. '<br>';
}
}
从上面的代码中,我正在获取图像旁边的“无替代文字”的图像和文字,但我想得到img标签出现的行号。 例如,这里的行号是57,
56. <div class="work_item">
57. <p class="pich"><img src="images/works/1.jpg" alt=""></p>
58. </div>
答案 0 :(得分:1)
使用DOMNode::getLineNo()
,例如$line = $image->getLineNo()
。
答案 1 :(得分:0)
HTML没有真正的行号概念,因为它们只是空格。
考虑到这一点,您可以计算目标节点之前的所有文本节点中有多少换行符。您可以使用DOMXPath执行此操作:
$xpath = new DOMXPath($doc);
$node = /* your target node */;
$textnodes = $xpath->query("./preceding::*[contains(text(),'\n')]",$node);
$line = 1;
foreach($textnodes as $textnode) $line += substr_count($textnode->textContent,"\n");
// $line is now the line number of the node.
请注意我没有测试过这个,也没有在xpath中使用过轴。
答案 2 :(得分:0)
我想我已经想出了我想要实现的目标,但不确定是正确的方法。它正在做这项工作。请留下评论或任何其他想法我如何改进它。 如果您转到以下站点并键入任何URL。它将在网页中生成包含可访问性问题的报告。它是一种辅助功能检查工具。
http://valet.webthing.com/page/
我想做的就是实现那种布局。下面的代码将生成提供的URL的DOM,并找到没有替代文本的任何图像标记。
<html>
<body>
<?php
$dom = new domDocument;
// load the html into the object
$dom->loadHTMLFile('$yourURLAddress');
// keep white space
$dom->preserveWhiteSpace = true;
// nicely format output
$dom->formatOutput = true;
$new = htmlspecialchars($dom->saveHTML(), ENT_QUOTES);
$lines = preg_split('/\r\n|\r|\n/', $new); //split the string on new lines
echo "<pre>";
//find 'alt=""' and print the line number and html tag
foreach ($lines as $lineNumber => $line) {
if (strpos($line, htmlspecialchars('alt=""')) !== false) {
echo "\r\n" . $lineNumber . ". " . $line;
}
}
echo "\n\n\nBelow is the whole DOM\n\n\n";
//print out the whole DOM including line numbers
foreach ($lines as $lineNumber => $line) {
echo "\r\n" . $lineNumber . ". " . $line;
}
echo "</pre>";
?>
</body>
</html>
我要感谢所有帮助过特别“chwagssd”和Mike Johnson的人。