How do I trigger WP CLI DB export using a PHP function?

WP-CLI can evaluate a PHP file.

See wp eval-file {PHP file name} for details, but essentially you:

  1. Write a PHP file containing the commands you want executed in WordPress’s context (let’s say you call it myfile.php)
  2. Run it using WP-CLI: wp eval-file myfile.php

If you need it scheduled, you could use cron, the Windows Scheduler, or whatever your local OS provided to schedule tasks.

Update 1

On re-reading your question, this might be more what you’re looking for (essentially you want to run a shell script at a scheduled time).

  1. Create a shell script (let’s suppose it’s located at /home/you/wp-backup.sh:

    #!/bin/sh
    /usr/local/bin/wp  --path=/var/www/ db export
    
  2. Add that script to your crontab using crontab -e:

    0 0 * * * /bin/sh /home/you/wp-backup.sh
    

…which would run the job every day at midnight. (See the crontab quick reference for more options.)

This also assumes that the sh shell is located at /bin/sh and wp is at /usr/local/bin/wp. If not, please adjust the code accordingly.

Update 2

From the comments, what you’re looking for is how to emulate wp db export in a WordPress context. I’m afraid I have what may be bad news.

Looking into the wp db source, it appears that the export command essentially uses PHP’s exec() command to run mysqldump. I don’t think you’d be wise to emulate this — I feel there are security experts who are cringing at just the thought of it.

There do exist WordPress backup plugins that can export your database; you can look into them (or, if they’re open source, examine their code to see if anything in there can help you out).