Finding part with simple html dom parser by two or more attributes per one element

孤街醉人 提交于 2020-06-25 04:55:08

问题


I would like to say, that I know, that many think, that Simple HTML DOM parser is a really bad choice for HTML parser. Still I need to use it at the moment.

I read some articles where it was described how to search by two or more attributes per one element. They proposed something like that and one possibility with array filtering

foreach ( tag[attr1=value] as tag1 )
{
   foreach ( tag[attr2=value] as tag2 )
   {
      // print tag2[attr1=value,attr2=value]
   }
}

My question is about native posibility for finding part by two attributes. I didn't find it in the manual, but not everything is always in the manual.

Does anyone know is there such way or similar tag2[attr1=value,attr2=value] or tag2[attr1=value attr2=value] or etc.?


回答1:


$doc      = new DOMDocument();
@$doc->loadHTML( $html );
$xpath    = new DOMXpath( $doc );
$elements = $xpath->query( "//*/div[@class='name'][@id='someId']" );  

if ( $elements->length > 0 )
{
    foreach ( $elements as $index => $node )
    {
        //get node detail here
    }
}



回答2:


As I see there is no way to do that at the moment. It should be edited by author of this script or by some other developer/s willing to continue the development of this project. Don't know does the license allow it or not.




回答3:


probably after 8 years they have came up with an updated version.

To use simple HTML dom parser with more than 1 attribute,

foreach($dom->find('tag[attr1][attr2]') as $stuff){
    echo $stuff;
}

Hope it helps.




回答4:


Never used Simple HTML DOM parser before. But its homepage says it works in jQuery way, so try tag[attr1=value][attr2=value] (jQuery: Multiple Attribute Selector)




回答5:


As far as I can tell having looked through the simple_html_dom, there is no way other than a nested foreach loop to achieve the functionality you are looking for. There is no inbuilt support for tag[attr=val][attr2=val]

Additionally each selector acts simply to add to the returned nodes, never to take away from it so something like tag.class[attr=val] or tag#id[attr=val] which I tried as a work around which would have mimicked some similar functionality.

As well, I tried $html->find("div[attr=val]")->find("div[attr2=val2]") but this also failed as Simple HTML DOM returns an array of nodes rather than a new tree object making chaining impossible.

The best way to go is the way you've posted in your question.



来源:https://stackoverflow.com/questions/5604411/finding-part-with-simple-html-dom-parser-by-two-or-more-attributes-per-one-eleme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!