如何获取 htm 元素的样式属性和行号


How to get style attributes and line number of htm elements?

我已经尝试了以下内容,但它无法正常工作,它给了我所有类型的标签,还有没有样式属性的标签。

  1. 使用 curl() 加载网站
  2. 将 html 正文从 curl 添加到名为:$bodyhtml的变量
  3. 使用 preg_match_all 查找页面上的所有样式属性,但未按预期工作。

我preg_match_all:

preg_mathc_all = preg_match_all('/(<[^>]+) style=".*?"/i', $bodyhtml, $matches);
获取

样式属性值的最佳方法是什么,如果可能的话,获取文档中找到它的行?

感谢您到目前为止的帮助。我最终使用了 DOM,并且正在按应有的方式工作:)谢谢!

我一直在尝试找到一个函数/类,它可以在文档中找到该行是 DOM 或 HTML 字符串。

但到目前为止没有运气。

有人有好方法吗?

说了"应该很容易完成",我想我会尝试一下,现在不得不承认它并不像我最初想象的那么简单。以下内容接近,有人(OP)可能希望花一些时间研究它,看看它可以改进的地方。

注释/评论的方式很少,所以我可能会因此被投票否决,但我把它留在这里,希望 op 可以使其更准确(它不远了!

$url='http://stackoverflow.com/questions/34998468/how-to-get-style-attributes-and-line-number-of-htm-elements#34998468';
$tmp=tempnam( sys_get_temp_dir(), 'html' );
file_put_contents( $tmp, file_get_contents( $url ) );
$dom=new DOMDocument;
$dom->loadHTMLFile( $tmp );
$xp=new DOMXPath( $dom );/* the xpath query could be improved */
$col=$xp->query( '//*[@style]', $dom->getElementsByTagName('body')->item(0) );
if( $col ){
    $data=array();
    /* iterate through nodes found by xpath query */
    foreach( $col as $node ){
        $tag=$node->tagName;
        $value=$node->nodeValue;
        $style=$node->getAttribute('style');
        /* create array for later use */
        $data[]=(object)array( 'tag'=>$tag, 'style'=>$style, 'html'=>trim( strip_tags( $value ) ) );
    }
    /* connect to the new file */
    $spl=new SplFileObject( $tmp );
    /* iterate through array found from xpath */
    foreach( $data as $key => $obj ){
        $str=$obj->html;
        $i=1;
        if( !empty( $str ) && strlen( $str ) > 1 ){/* ignore empty strings */
            $spl->fseek( 0 );
            while( !$spl->eof() ) {/* read the html source file line by line + make matches */
                if( stristr( $spl->fgetss(), $str ) ) {
                    echo 'line: '.$i.', tag: '.$obj->tag.', html:'.$str.', style:'.$obj->style.BR;
                    break;  
                }
                $i++;
            }
        }
    }
}
@unlink( $tmp );
$dom = $xp = $col = $spl = $tmp = null;