We help IT Professionals succeed at work.

PHP delete contents of file- before writing to it

Jon Imms
Jon Imms asked
on
3,752 Views
Last Modified: 2017-03-16
could somebody help me with the following php/wordpress script?

I have created a cron job, which will write all post data to a custom XML file.  The Cron job is set to go once daily, and works,  but the problem i am having is that, it does not delete the contents of the file each night,  just adds to the original file, making duplicate entries.

How would i change the script below, so that the first thing the script does is empy the file, before writing the data each day.


//add_filter( 'save_post', 'xml_feed_creation_rr');

if ( ! wp_next_scheduled( 'xml_generate_cron_hook_rr' ) ) {
    wp_schedule_event( time(), 'daily', 'xml_generate_cron_hook_rr' );
}

add_action( 'xml_generate_cron_hook_rr', 'xml_generate_cron_exec_rr' );


function xml_generate_cron_exec_rr(){
    file_put_contents('/filepath/wp-content/themes/Avada-Child/RRfeed.xml', '');

    $numposts = 50000; // number of posts in feed
    $posts = query_posts('showposts='.$numposts.'');
    $more = 1;

    $xmlWriter = new XMLWriter();
    $xmlWriter->openMemory();
    $xmlWriter->setIndent(true);
    $xmlWriter->startDocument('1.0', 'UTF-8');
    $xmlWriter->startElement('source');
    $xmlWriter->writeElement('publisher', 'Myself');
    $xmlWriter->writeElement('publisherurl', 'http://mysite.com/');
    $xmlWriter->writeElement('lastBuildDate', mysql2date('D, d M Y H:i:s +0000', strtotime('Today')));

    $counter = 0;
    while(have_posts()) : the_post(); ?>
        <?php $zips = get_field('zipcode');
        $zips_array = explode(' ',$zips);
        foreach($zips_array as $zip){
            $counter++;
            $xmlWriter->startElement('job');

            $xmlWriter->startElement('title');
            $xmlWriter->writeCData( get_the_title_rss() );
            $xmlWriter->endElement();

            $xmlWriter->startElement('date');
            $xmlWriter->writeCData( mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false) );
            $xmlWriter->endElement();

            $xmlWriter->startElement('referencenumber');
            $xmlWriter->writeCData( get_the_id().$zip );
            $xmlWriter->endElement();

            $xmlWriter->startElement('url');
            $xmlWriter->writeCData( get_permalink() );
            $xmlWriter->endElement();

            $xmlWriter->startElement('company');
            $xmlWriter->writeCData( 'Compnay' );
            $xmlWriter->endElement();

            $xmlWriter->startElement('city');
            $xmlWriter->writeCData( get_field('city') );
            $xmlWriter->endElement();

            $xmlWriter->startElement('state');
            $xmlWriter->writeCData( get_field('state') );
            $xmlWriter->endElement();

            $xmlWriter->startElement('country');
            $xmlWriter->writeCData( 'US' );
            $xmlWriter->endElement();

            $xmlWriter->startElement('postalcode');
            $xmlWriter->writeCData( $zip );
            $xmlWriter->endElement();

            if (get_option('rss_use_excerpt')) :

                $xmlWriter->startElement('description');
                $xmlWriter->writeCData( get_the_excerpt() );
                $xmlWriter->endElement();

                $xmlWriter->startElement('applylink');
                $xmlWriter->writeCData( 'https://intelliapp2.driverapponline.com/c/cr?r=XMLFeed' );
                $xmlWriter->endElement();

            else :
                $xmlWriter->startElement('description');
                $xmlWriter->writeCData( get_the_excerpt() );
                $xmlWriter->endElement();

                $xmlWriter->startElement('applylink');
                $xmlWriter->writeCData( 'https://intelliapp2.driverapponline.com/c/cr?r=XMLFeed' );
                $xmlWriter->endElement();

                if ( strlen( get_the_content() ) > 0 ) :

                    $xmlWriter->startElement('content');
                    $xmlWriter->writeCData( apply_filters('the_content', get_the_content()) );
                    $xmlWriter->endElement();

                else :

                    $xmlWriter->startElement('content');
                    $xmlWriter->writeCData( apply_filters('the_content', get_the_excerpt()) );
                    $xmlWriter->endElement();

                endif;
            endif;

            $xmlWriter->startElement('salary');
            $xmlWriter->writeCData( do_shortcode( get_post_meta( get_the_id(), 'salary', true ) ) );
            $xmlWriter->endElement();

            $xmlWriter->startElement('experience');
            $xmlWriter->writeCData( do_shortcode( '[Qualifications]' ) );
            $xmlWriter->endElement();

            $xmlWriter->startElement('jobtype');
            $xmlWriter->writeCData( get_field('jobtype') );
            $xmlWriter->endElement();

            $xmlWriter->startElement('category');
            $xmlWriter->writeCData( strip_tags(get_the_category_list(' ')) );
            $xmlWriter->endElement();

            $xmlWriter->endElement();

            // Flush XML in memory to file every 1000 iterations
            if (0 == $counter%1000) {
                file_put_contents('/filepath/wp-content/themes/Avada-Child/RRfeed.xml', $xmlWriter->flush(true), FILE_APPEND);
            }
        }
    endwhile;
    $xmlWriter->endElement();
    $xmlWriter->endDocument();
    //Final flush to make sure we haven't missed anything
    file_put_contents('/filepath/wp-content/themes/Avada-Child/RRfeed.xml', $xmlWriter->flush(true), FILE_APPEND);

}

Open in new window

Comment
Watch Question

Most Valuable Expert 2011
Author of the Year 2014

Commented:
To delete a file you can use unlink()

If you don't want to append to the existing file, you can remove FILE_APPEND from line 124 and 131.
http://php.net/manual/en/function.file-put-contents.php

After you remove FILE_APPEND line 11 will not be necessary because the RRfeed.xml will be overwritten.
CERTIFIED EXPERT

Commented:
You can use fopen with 'w' which will truncate the file

 fopen('/filepath/wp-content/themes/Avada-Child/RRfeed.xml', 'w');

Open in new window


http://www.php.net/manual/en/function.fopen.php
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Why would you use fopen() when the script is already using file_put_contents()?  That just sounds like a red herring, when all you have to do is remove FILE_APPEND from the file_put_contents() statement.
Jon ImmsWeb Developer

Author

Commented:
So just to be double sure.

I put the Unlink at the very top,  -- that deletes the file or contents.

Then I create the file with the new fresh data.

I had the FILE_APPEND in because the XML file is very big, so wanted to cut down memory usage etc.

//add_filter( 'save_post', 'xml_feed_creation_rr');

if ( ! wp_next_scheduled( 'xml_generate_cron_hook_rr' ) ) {
    wp_schedule_event( time(), 'daily', 'xml_generate_cron_hook_rr' );
}

add_action( 'xml_generate_cron_hook_rr', 'xml_generate_cron_exec_rr' );


function xml_generate_cron_exec_rr(){
   
// Delete the existing file
     unlink('/filepath/wp-content/themes/Avada-Child/RRfeed.xml);

// Create new file.
    file_put_contents('/filepath/wp-content/themes/Avada-Child/RRfeed.xml', '');

    $numposts = 50000; // number of posts in feed
    $posts = query_posts('showposts='.$numposts.'');
    $more = 1;

    $xmlWriter = new XMLWriter();
    $xmlWriter->openMemory();
    $xmlWriter->setIndent(true);
    $xmlWriter->startDocument('1.0', 'UTF-8');
    $xmlWriter->startElement('source');
    $xmlWriter->writeElement('publisher', 'Myself');
    $xmlWriter->writeElement('publisherurl', 'http://mysite.com/');
    $xmlWriter->writeElement('lastBuildDate', mysql2date('D, d M Y H:i:s +0000', strtotime('Today')));

    $counter = 0;
    while(have_posts()) : the_post(); ?>
        <?php $zips = get_field('zipcode');
        $zips_array = explode(' ',$zips);
        foreach($zips_array as $zip){
            $counter++;
            $xmlWriter->startElement('job');

            $xmlWriter->startElement('title');
            $xmlWriter->writeCData( get_the_title_rss() );
            $xmlWriter->endElement();

            $xmlWriter->startElement('date');
            $xmlWriter->writeCData( mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false) );
            $xmlWriter->endElement();

            $xmlWriter->startElement('referencenumber');
            $xmlWriter->writeCData( get_the_id().$zip );
            $xmlWriter->endElement();

            $xmlWriter->startElement('url');
            $xmlWriter->writeCData( get_permalink() );
            $xmlWriter->endElement();

            $xmlWriter->startElement('company');
            $xmlWriter->writeCData( 'Compnay' );
            $xmlWriter->endElement();

            $xmlWriter->startElement('city');
            $xmlWriter->writeCData( get_field('city') );
            $xmlWriter->endElement();

            $xmlWriter->startElement('state');
            $xmlWriter->writeCData( get_field('state') );
            $xmlWriter->endElement();

            $xmlWriter->startElement('country');
            $xmlWriter->writeCData( 'US' );
            $xmlWriter->endElement();

            $xmlWriter->startElement('postalcode');
            $xmlWriter->writeCData( $zip );
            $xmlWriter->endElement();

            if (get_option('rss_use_excerpt')) :

                $xmlWriter->startElement('description');
                $xmlWriter->writeCData( get_the_excerpt() );
                $xmlWriter->endElement();

                $xmlWriter->startElement('applylink');
                $xmlWriter->writeCData( 'https://intelliapp2.driverapponline.com/c/cr?r=XMLFeed' );
                $xmlWriter->endElement();

            else :
                $xmlWriter->startElement('description');
                $xmlWriter->writeCData( get_the_excerpt() );
                $xmlWriter->endElement();

                $xmlWriter->startElement('applylink');
                $xmlWriter->writeCData( 'https://intelliapp2.driverapponline.com/c/cr?r=XMLFeed' );
                $xmlWriter->endElement();

                if ( strlen( get_the_content() ) > 0 ) :

                    $xmlWriter->startElement('content');
                    $xmlWriter->writeCData( apply_filters('the_content', get_the_content()) );
                    $xmlWriter->endElement();

                else :

                    $xmlWriter->startElement('content');
                    $xmlWriter->writeCData( apply_filters('the_content', get_the_excerpt()) );
                    $xmlWriter->endElement();

                endif;
            endif;

            $xmlWriter->startElement('salary');
            $xmlWriter->writeCData( do_shortcode( get_post_meta( get_the_id(), 'salary', true ) ) );
            $xmlWriter->endElement();

            $xmlWriter->startElement('experience');
            $xmlWriter->writeCData( do_shortcode( '[Qualifications]' ) );
            $xmlWriter->endElement();

            $xmlWriter->startElement('jobtype');
            $xmlWriter->writeCData( get_field('jobtype') );
            $xmlWriter->endElement();

            $xmlWriter->startElement('category');
            $xmlWriter->writeCData( strip_tags(get_the_category_list(' ')) );
            $xmlWriter->endElement();

            $xmlWriter->endElement();

            // Flush XML in memory to file every 1000 iterations
            if (0 == $counter%1000) {
                file_put_contents('/filepath/wp-content/themes/Avada-Child/RRfeed.xml', $xmlWriter->flush(true), FILE_APPEND);
            }
        }
    endwhile;
    $xmlWriter->endElement();
    $xmlWriter->endDocument();
    //Final flush to make sure we haven't missed anything
    file_put_contents('/filepath/wp-content/themes/Avada-Child/RRfeed.xml', $xmlWriter->flush(true), FILE_APPEND);

}

Open in new window

Most Valuable Expert 2011
Author of the Year 2014
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Jon ImmsWeb Developer

Author

Commented:
Brilliant,  I get it now.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.