Simple HTML DOM getting all attributes from a tag

前端 未结 4 1744
攒了一身酷
攒了一身酷 2020-12-15 13:18

Sort of a two part question but maybe one answers the other. I\'m trying to get a piece of information out of an

4条回答
  •  情歌与酒
    2020-12-15 13:50

    To grab all those attributes, you should before investigate the parsed element, like this:

    foreach($html->find('div[class=bar] a') as $a){
      var_dump($a->attr);
    }
    

    ...and see if those attributes exist. They don't seem to be valid HTML, so maybe the parser discards them.

    If they exist, you can read them like this:

    foreach($html->find('div[class=bar] a') as $a){
      $article = array($a->href, $a->innertext);
      if (isset($a->attr['data1'])) {
        $article['data1'] = $a->attr['data1'];
      }
      if (isset($a->attr['data2'])) {
        $article['data2'] = $a->attr['data2'];
      }
      //...
      $articles[] = $article;
    }
    

    To get both classes you can use a multiple selector, separated by a comma:

    foreach($html->find('div[class=bar] a, div[class=bar2] a') as $a){
    ...
    

提交回复
热议问题