PHP Simple HTML DOM Parser : Select two classes

萝らか妹 提交于 2019-12-11 02:19:58

问题


My problem is very simple . Let's say I have multiple 'a' :

    <td class="autoindex_td">

        <a class="autoindex_a snap_shots" href="http://example.com.html">
            <img height="16" width="16" src="http://exmple.com/download/index_icons/winxp/sound.png" alt="[mp3]"></img>
            <strong>

                05 - example.mp3

            </strong>
        </a>
   </td>

I just want to find 'strong' which has two classes . Here what I tried :

foreach ($html->find('a[class=autoindex_a , class=snap_shots]') as $link) {
    if(isset($link)){
   foreach($link->find('strong') as $tag)
       {
             $name = $tag->plaintext ;
             $hiren[] = $name ;
       }
     }
   }

But I get null .So how do I select two class at the same time ?


回答1:


Just found a way :

 foreach ($html->find('a[class=autoindex_a snap_shots]') as $link) {
    if(isset($link)){
   foreach($link->find('strong') as $tag)
       {
             $name = $tag->plaintext ;
             $hiren[] = $name ;
       }
     }
   }



回答2:


Why not DOMDocument Class ?

<?php

$html=' <td class="autoindex_td">

        <a class="autoindex_a snap_shots" href="http://example.com.html">
            <img height="16" width="16" src="http://exmple.com/download/index_icons/winxp/sound.png" alt="[mp3]"></img>
            <strong>

                05 - example.mp3

            </strong>
        </a>
   </td>';

$dom = new DOMDocument;
@$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $tag) {
    if ($tag->getAttribute('class') === 'autoindex_a snap_shots') {
        foreach($tag->getElementsByTagName('strong') as $strongTag)
        {
        echo $strongTag->nodeValue; //"prints"  05 - example.mp3
        }
    }
}



回答3:


You need to separate the attribute finders as:

$html->find("a[class='autoindex_a'][class='snap_shots']")

or, separate the classes with a dot . separator:

$html->find('a.autoindex_a.snap_shots')


来源:https://stackoverflow.com/questions/21473522/php-simple-html-dom-parser-select-two-classes

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