Skip to main content

WordPress Export Manipulation using PHP

Robert Bates | Senior Software Engineer

August 25, 2015


In the world of content management systems (CMS), WordPress is one of the mainstays of bloggers, for individuals or organizations, public or private. However, sometimes there’s a requirement to migrate WordPress content into a different CMS that provides more generalized functionality. When this happens, the core WXR export is a lifesaver. WXR stands for WordPress eXtended RSS, which is exactly what the WXR format is - a giant RSS dump of the site’s content, media, and tagging system. WordPress extends RSS to support all its custom elements via the “wp” namespace which keeps the content RSS compliant while adding what’s needed to replicate the site’s content in its entirety. The WXR format is the quickest way to export and import data between WordPress sites as well as for use as an archiving tool. It also happens to work really well as a source for migrations into alternate systems...

One Site to Rule Them All

I recently worked on a project where a new site was being built in Drupal 7, and a requirement had surfaced to migrate multiple WordPress sites into the single Drupal site, with each post being tagged in Drupal to associate it with the original source site for categorical blogrolls. We chose to leverage the WordPress category system to accomplish our goal. Great! We now have a set of WXR files and a plan of action - now how do we get the data into Drupal? Here is where the very functional WordPress Migrate module came into play. This module leverages the Migrate module’s new wizard UI introduced in version 2.6, and steps the admin through building a dynamic migration with uploaded file (or source WordPress site, if you have all the credentials), field mappings, and behavior. We can conveniently map the WordPress category tags to the appropriate term reference field on our target Blog content type. But there’s the catch - the exported data has multiple legacy categories, where we need one new one, per WXR dump…

PHP DOM FTW!

Let’s see… XML manipulation at the element level. Ease of coding. PHP + DOM to the rescue! Of course, you could use something like SimpleXML and override all kinds of parsing callbacks, but the DOM model and class hierarchy make it the quick and dirty choice for a one-off XML manipulation. First off, we need to define a class that can handle any WXR-specific features that we want to expose, so we derive a new class from DOMDocument:

// Define custom DOMDocument class.
class WXRDocument extends DOMDocument {
  public $wp_ns_uri = '';
  private $term_id_max = 0;

  // Override load method so we can extract the wp namespace URI.
  public function load($filename, $options = 0) {
    $retval = parent::load($filename, $options);
    if (FALSE !== $retval) {
      // Extract wp namespace URI from document.
      $this->wp_ns_uri = $this->lookupNamespaceURI('wp');

      // Find max value of term ids.
      foreach (array('category', 'tag') as $el_name) {
        $terms = $this->getElementsByTagNameNS($this->wp_ns_uri, $el_name);
        foreach ($terms as $term) {
          $term_id = $term->getElementsByTagNameNS($this->wp_ns_uri, 'term_id');
          $this->term_id_max = max($this->term_id_max, $term_id->item(0)->textContent);
        }
      }
    }

    return $retval;
  }

  // Add new method to create new WP categories in the WXR file.  Array key is nicename, value is cat_name.
  public function addCategories($new_cats = array()) {
    $channels = $this->getElementsByTagName('channel');
    $channel = $channels->item(0);
    foreach ($new_cats as $nicename => $cat_name) {
      $new_cat = $this->createElementNS($this->wp_ns_uri, 'wp:category');
      $new_cat->appendChild($this->createElementNS($this->wp_ns_uri, 'wp:term_id', ++$this->term_id_max));
      $new_cat->appendChild($this->createElementNS($this->wp_ns_uri, 'wp:category_nicename', $nicename));
      $new_cat->appendChild($this->createElementNS($this->wp_ns_uri, 'wp:category_parent'));
    
      $new_cat_name = $this->createElementNS($this->wp_ns_uri, 'wp:cat_name');
      $new_cat_name->appendChild(new DOMCdataSection($cat_name));
      $new_cat->appendChild($new_cat_name);
      $channel->appendChild($new_cat);
    }
  }
}

Our primary goal for this class is to load the WXR file, extract the namespace information, and initialize properties related to managing categories at the document level. The method addCategories allows us to arbitrarily add more categories to the document without having to worry about term ID collisions and abstracts it so we can focus on what we need to do in our code, not how to do it. This will allow us to add the new categories for each site at the export level, which is analogous to managing a vocabulary in Drupal. Next up, we need to be able to manipulate individual posts to remove all old category tags and add our new ones. This is also accomplished by extending a built-in PHP class, DOMElement:

// Define custom DOMElement class.
class WXRElement extends DOMElement {
  public function setCategory($nicename, $cat_name) {
    // Remove all existing categories.
    $cats = $this->getElementsByTagName('category');
    foreach ($cats as $cat) {
      if ('category' == $cat->getAttribute('domain')) {
        $this->removeChild($cat);
      }
    }

    // Set desired category.
    $new_cat = $this->ownerDocument->createElement('category');
    $new_cat->appendChild(new DOMCdataSection($cat_name));
    $new_cat->setAttribute('domain', 'category');
    $new_cat->setAttribute('nicename', $nicename);
    $this->appendChild($new_cat);
  }
}

The setCategory method will allow us to provide a single category that we want to replace all existing categories with on a single post. Again, this is a convenience method to simplify our WXR manipulation code and abstract the more complex DOM manipulation away from our core script logic. Now that we have all our classes in place, let’s import the WXR document and register our element class:

// Set up DOM document for manipulation.
$xml_filename = 'blog1-export.xml';
print "Processing {$xml_filename}\n";
$doc = new WXRDocument();
$doc->registerNodeClass('DOMElement', 'WXRElement');
$doc->load($xml_filename);

OK, the WXR file has now been loaded into an instance of our new class, and the elements are all being instantiated as WXRElement objects. Now that we’ve got the DOM document prepped and ready to go, let’s add our new category to the top level in a couple lines:

// Add new categories.
$new_cats = array(
  'category-blog-1' => "Blog Site 1",
);
$doc->addCategories($new_cats);

We could have added a plethora of categories at this point, but in this case we only needed the one new one. Now that the category has been added, let’s locate our post elements and update them:

// Iterate over WP items looking for posts.
$items = $doc->getElementsByTagName('item');
foreach ($items as $item) {
  $post_type = $item->getElementsByTagNameNS($doc->wp_ns_uri, 'post_type');
  if ('post' == $post_type->item(0)->textContent) {
    // Set new post category.
    $nicename = 'category-blog-1';
    $category = $new_cats[$nicename];
    $item->setCategory($nicename, $category);
  }
}

Note that the code supports potential logic to pick a $nicename value based on the post’s content; in this simplified version we only have the one category. The code searches all elements for WXR signatures for post metadata, and then directly updates the category information on the post element. We could have added some iterator logic to the WXRDocument class and type-identification methods to the WXRElement class, but we weren’t going for OO perfection, just basic functionality and speed with convenience. Now that we’ve added the new category to the document and updated all posts in the export to use the new category, we’re ready to save it out:

// Save out proce// Save out processed XML.
$save_filename = pathinfo($xml_filename, PATHINFO_FILENAME) . '-processed.xml';
print "Saving {$save_filename}\n";
$doc->save($save_filename);

We now have a modified WXR file with the proper category tagging to import into Drupal, and the WordPress Migrate module will have no problem processing it. Minor modifications to update the source filename and target category are all that’s required for subsequent runs. Luckily we only had a few to process so it went quickly after the initial script was written.

Closing Notes

The WXRDocument and WXRElement classes defined above are not provided as the be-all, end-all for WXR DOM manipulation. Instead, they were a proof of concept regarding how the DOM base classes in PHP can be extended to provide customized XML doctype support, and possibly a good starting point for an extensible WXR-friendly solution in the event requirements changed mid-project. Where possible, the methods were coded with reusability in mind and support for multi-value parameters via arrays, with single values being the edge case. If you’ve got experience with manipulating WXR exports or extending the DOM class library, drop a comment in below!


Recommended Next
Development
A Developer's Guide For Contributing To Drupal
Black pixels on a grey background
Development
3 Steps to a Smooth Salesforce Integration
Black pixels on a grey background
Development
Drupal 8 End of Life: What You Need To Know
Woman working on a laptop
Jump back to top