3

I have the following tags

<div class="col *">Text</div>

* is anything.

I want to get all div tag with class attribute contains col (as in my example) using Simple HTML DOM.

hakre
  • 193,403
  • 52
  • 435
  • 836
aye
  • 301
  • 2
  • 16

2 Answers2

17

Since Simple HTML DOM does already have a method for selecting attributes that contain a certain value and|or something else. For example

$html->find("div[class*=col]", 0)->outertext

Or you could just retrieve div nodes that start with col like so

$html->find("div[class^=col]", 0)->outertext

And for safe keeping you can find all the other ways to filter attributes in this 3rd party plugin (By the way there are way better things for dealing with DOM that are based on libxml, a definitive list can be found here)

  1. [attribute] - Matches elements that have the specified attribute.
  2. [!attribute] - Matches elements that don't have the specified attribute.
  3. [attribute=value] - Matches elements that have the specified attribute with a certain value.
  4. [attribute!=value] - Matches elements that don't have the specified attribute with a certain value.
  5. [attribute^=value] - Matches elements that have the specified attribute and it starts with a certain value.
  6. [attribute$=value] - Matches elements that have the specified attribute and it ends with a certain value.
  7. [attribute*=value] - Matches elements that have the specified attribute and it contains a certain value.

Source: http://simplehtmldom.sourceforge.net/manual.htm

Community
  • 1
  • 1
Morgan Wilde
  • 16,795
  • 10
  • 53
  • 99
  • 1
    This is really an excellent summary of the simple_html_dom functionalities. Thank you very much – aye Dec 01 '12 at 15:39
0

I don't have a way how to test it at the moment, but as I looked into it (http://simplehtmldom.sourceforge.net/) it should be fairly simple.

$html = file_get_html('http://somesite.net');
foreach($html->find('div') as $div){
  if stripos($div->class,"col"){
    // this $div has a "col" class..
  }
}

or even simpler:

$html = file_get_html('http://somesite.net');
foreach($html->find('div.col') as $div){
  // every $div has a "col" class..
}

Does it work?

Smuuf
  • 6,339
  • 3
  • 23
  • 35
  • I'm looking for a similar solution to the second method since it is grammatically simpler, but it does not work. I think the second method only find div with the `class="col"`, not `class="col *"` – aye Nov 23 '12 at 08:35
  • That shouldn't be true. The class selector selects an object with said class even if it has more of those.. – Smuuf Nov 23 '12 at 09:11