0

Possible Duplicate:
Selecting a css class with xpath

I am trying to extract the source for all images inside a html like this

    <li class="carousel_item">
    <img src="http://www.xxxx.com/1fc1c1c2db5852e08ffcff38.jpg" 
                        width="200" 
                        height="200" 

                        style="margin-bottom:1px" 
                        class="image_error" /> 
                    <span class="image_error" title="jpg"></span> 
                    <span class="image_error" title="2.jpg"></span> 
                </li> 

When I use the following commands I get all images in the document

   $nodelist = $xpath->query( "//img/@src" );
   foreach ($nodelist as $n){
    echo  $n->nodeValue."<br>";
 }

but I want just the items listed in the class="carousel_item"

Is this possible?

Community
  • 1
  • 1
user1197941
  • 179
  • 3
  • 16

2 Answers2

1

Sure, just include the <li> and its class attribute in the query. You just need to change the xpath string to:

$nodelist = $xpath->query( "//li[@class='carousel_item']/img/@src" );

Demo

nickb
  • 59,313
  • 13
  • 108
  • 143
  • the class attribute in HTML is a space separated list which makes it a bit less trivial. Technically what you answered here must not be wrong, but must not be right as well. – hakre Jun 13 '12 at 16:26
  • @hakre - Good point - If this is the case user1197941, you'd have to replace the class selector with the `contains()` function, which bsdnoobz just pointed out. – nickb Jun 13 '12 at 16:29
  • Well @bsdnoobz is a bit fast with answering and so it's quite short as well. You want to know the whole truth? Here is my blog post explaining the details [CSS Selector to XPath conversion](http://hakre.wordpress.com/2012/03/18/css-selector-to-xpath-conversion/) and here is the xpath: `//*['P' = translate(name(.), 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')]/@*['CLASS' = translate(name(.), 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') and contains(concat(' ', normalize-space(.), ' '), concat(' ', 'intro', ' '))]` - that is for a `P` element with the class `intro`. – hakre Jun 13 '12 at 16:32
  • @hakre - Very interesting read! Just bookmarked it, thanks for the info – nickb Jun 13 '12 at 16:40
1
$nodelist = $xpath->query('//li[contains(@class, "carousel_item")]/img/@src');
flowfree
  • 16,356
  • 12
  • 52
  • 76