views:

2573

answers:

5

I want to use the php simple HTML DOM parser to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set_callback which Sets a callback function. However im not sure what this does or how I would use it? In one of the examples its used to call a function which strips out some stuff, im wondering if you have to use this to call all functions?

I guess im wondering why I use this, and what does it do as I have never come across a callback function before!

+4  A: 

Here's a basic callback function example:

<?php

function thisFuncTakesACallback($callbackFunc)
{
    echo "I'm going to call $callbackFunc!<br />";
    $callbackFunc();
}

function thisFuncGetsCalled()
{
    echo "I'm a callback function!<br />";
}

thisFuncTakesACallback( 'thisFuncGetsCalled' );
?>

You can call a function that has its name stored in a variable like this: $variable().

So, in the above example, we pass the name of the thisFuncGetsCalled function to thisFuncTakesACallback() which then calls the function passed in.

Mark Biek
+1  A: 

A callback function will use that function on whatever data is returned by a particular method.

I'm not sure how this particular library works, but it could be something as simple as:

$html = file_get_html('http://example.com');
$html->set_callback('make_bold');
$html->find('#title'); // returns an array

function make_bold($results) {
// make the first result bold
  return '<b>'.$results[0].'</b>';
}

ie, The function "make_bold()" will be run on any data found. Again, I'm not sure how this particular library works (ie, what methods the callback function will get called on)

Owen
A: 

I know you're asking about a callback, however if your using PHP5 it may be easier to use SimpleXml to pull the data you are looking for.

null
+1  A: 

A callback is either a function, an object instance' method, or a static method on a class. Either way, it's kind of a function pointer. In some languages, functions are a specific type. So you could assign a function to a variable. These are generally called function oriented languages. A good example is Javascript.

In PHP, a callback can be any of:

$fn = 'foo'; // => foo()
$fn = array($obj, 'foo'); // => $obj->foo()
$fn = array('Foo', 'bar'); // => Foo::bar()

See the manual entry for is_callable.

You can invoke a callback with the rather verbose function call_user_func.

troelskn
A: 

All the answers are great many thanks. I have awarded the best answer to the one that helped me the most. Many thanks

Paul M