WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Writing the HTML output of a Dynamic Sidebar to file (2 posts)

  1. GreenLead
    Member
    Posted 1 year ago #

    I need to write the HTML output of a sidebar and the widgets contained inside it into a text file.

    However, whilst calling dynamic_sidebar() and specifying the location does display the output, it simply returns "true" to the PHP code. Is there a way to get the actual HTML output and write that to a file instead?

  2. GreenLead
    Member
    Posted 1 year ago #

    To answer my own question and hopefully help others facing similar problems, here's my solution:

    (Take note of the annotations)

    <?php
    	// Put this at the start of the script
    
    	ob_start();
    
    	// Initialize WordPress, etc
    
    	require('wp-config.php');
    	$wp->init();
    	$wp->parse_request();
    	$wp->query_posts();
    	$wp->register_globals();
    
    	/*
    	Load the contents of a widget area.
    	Usually, dynamic_sidebar only returns "true" upon a successful function call, but as we'll see later on, the HTML output that is sent to the browser can be captured and saved to a file
    */
    
    	dynamic_sidebar( 'top-widget-area' );
    
    	// Get the contents of the file, which obstensibly contains the desired HTML output of the widget
    
    	$page = ob_get_contents();
    	ob_end_flush();
    
    	// Write the contents to a text file
    
    	$fp = fopen("menu.txt","w");
    	fwrite($fp,$page);
    	fclose($fp);
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.