tags:

views:

68

answers:

2

I've done this before but can't find my code snippet.

I'd like to parse an html file and pull everything into my browser that sits between some span tags. There are other span tags in the html that I do not want so I figured I would limit the parsing to just the span tags that have the same css class. Can someone please give me an example of how to do this? Thanks.

$tags = $doc->getElementsByTagName('span');


This is a single row of the html I am trying to parse

<span class='close'><a href="bla.com/test.htm">test row</a></span>
A: 

First attempt (untested):

$elts = $doc->getElementsByTagName('span');
foreach ($elts as $elt)
  {
    $className = $elt->getAttribute('class');
    if (array_search('close', explode(' ', $className)))
      {
        // Do things with $elt since it matches.
      }
  }
Dustin
Hey Dustin, thanks for the help. I'm almost certain that there is a way to append the css class name to the "getElementsByTagName" without having to use regex. If I can't get that syntax from anyone here, I will certainly use your suggestion
John
Original answer edited. It has been a while since I used PHP.
Dustin
Buddy, thank you. It works. I modified your code to use in_array() instead of array_search because I have an associative array and array_search wouldn't work. Other than that, It works great.
John
A: 

In my opinion and experience it can be done by getElementsByTagName() ?? Just use some ajax-y function to call for it and you have your DOM element :)

Ben Fransen
Hey Ben, I ultimately want to use this script to run as a cron job so AJAX won't work since AJAX only works in the browser. At the moment, I'm using the browser to test it.
John