Question

Basically I've set up a WPAlchemy metabox for the custom post type 'dealer' and I want to generate an XML file that contains formatted meta data from all of the dealer posts so that the data can be used for markers on a google map. Here's what I have in my functions.php file so far based off of Write to XML file using fopen in Wordpress

<?php function markers_xml() {
    if ($_POST['post_type'] == 'es_dealer') {
        $xml = new SimpleXMLElement('<xml/>');
        $markers = get_posts('post_type=es_dealer&posts_per_page=-1');

        $xml->addChild('markers');

        foreach($markers as $i=>$marker) {
            $name = get_the_title($marker->ID);
            $lat = get_post_meta($marker->ID, 'lat', true);
            $lng = get_post_meta($marker->ID, 'long', true);

            $xml->markers->addChild('marker');
            $xml->markers->marker[$i]->addAttribute('name', $name);
            $xml->markers->marker[$i]->addAttribute('lat', $lat);
            $xml->markers->marker[$i]->addAttribute('lng', $lng);
        }

        $file = 'http://encode-design.com/wp-content/uploads/test.xml';
        $open = fopen($file, 'w') or die ("File cannot be opened.");
        fwrite($open, $xml->asXML());
        fclose($open);
    }
}
add_action( 'save_post', 'markers_xml' ); ?>

When I save a dealer post I don't get a message saying 'File cannot be opened.' but there are no changes to the xml file either. I've set the xml file and the uploads folder permissions to 777 and fopen is enabled on my server. What am I missing? Any help would be much appreciated!

Was it helpful?

Solution 2

I switched to file_put_contents() instead of fopen, fwrite, and fclose and it did the trick! Also simplified my file path.

<?php 
$xml = new SimpleXMLElement('<xml/>');
$markers = get_posts('post_type=es_dealer&posts_per_page=-1');
$xml->addChild('markers');
foreach($markers as $i=>$marker) {
    global $dealer_mb;
    $meta = $dealer_mb->the_meta($marker->ID);
    $name = get_the_title($marker->ID);
    $lat = $meta['lat'];
    $lng = $meta['long'];

    $xml->markers->addChild('marker');
    $xml->markers->marker[$i]->addAttribute('name', $name);
    $xml->markers->marker[$i]->addAttribute('lat', $lat);
    $xml->markers->marker[$i]->addAttribute('lng', $lng);
}
$file = 'testing.xml';
$current = $xml->asXML();
file_put_contents($file,$current); 
?>

OTHER TIPS

Add this code to check whether writing to the file is successful.

if(!fwrite($open, $xml->asXML()))
{
    echo 'error';
}
else
{
    echo 'success'; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top