Finding part with simple html dom parser by two or

2020-07-22 19:43发布

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.?

5条回答
Explosion°爆炸
2楼-- · 2020-07-22 20:00
$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
    }
}
查看更多
对你真心纯属浪费
3楼-- · 2020-07-22 20:02

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.

查看更多
Animai°情兽
4楼-- · 2020-07-22 20:07

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.

查看更多
小情绪 Triste *
5楼-- · 2020-07-22 20:10

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)

查看更多
迷人小祖宗
6楼-- · 2020-07-22 20:21

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.

查看更多
登录 后发表回答