In the last phpTidbit, you've taken a glance at PHP3's variable functions. This issue shows a real life example (which by the way could be very useful): Parsing HTML for certain tags.
The following function html_parse parses a file or string for a tag and returns its content and attributes to a custom callback function (you've learned what this means in the last phpTidbit). This is useful if you want for example extract all headings from a file, create a list of all links or use it for custom templates. You don't have to learn XML just for this!
Currently there are some limitations:
- it handles only tags with an appropiate closing tag: <img>, <param> etc. won't work.
- attributes of the tag must be enclosed by double quotes (this could be changed easily though).
The principle of this function is simple:
Every time it encounters the tag you specified as parameter, it calls your callback function.
The syntax:
html_parse($html_file, $element_handler, $tag):
- $html_file: either a string containing a valid filename or a string containing HTML markup.
- $element_handler: your callback-function (see below for the parameters this function must accept)
- $tag: the tag you want to search for.
The following example extracts all <H2>-headings from "test.html" and displays them: