Read Adobe XMP / XML in PHP

I’ve found a few snippets of PHP code to read XMP / XML meta data from an image file, but none that I would call very robust or efficient. I ended up writing my own for Underwater Focus, and I’m quite pleased with the result. In fact, after adding support for a shortcode, I packaged it as an Adobe XMP plugin for WordPress.

The first part of using XMP meta data is reading the XMP information from the image. I’ve seen a few solutions that read the whole file into memory, and others that read-in just a small part. If the XMP / XML contains a lot of information, that small part may be incomplete. And each time the XMP meta data is required, the original (and sometimes quite large) image file must be re-read. Since the XMP doesn’t change unless the original image is updated, there’s no reason to keep re-reading the same large file time and time again.

The method I wrote reads a 64k chunk at a time, and keeps reading additional chunks until it finds the </x:xmpmeta> tag, or reaches the hard-coded limit of 500k. The extracted XMP information is then saved on disk, and if the function is called again for the same file, the cached information is used instead (provided the cache file’s modification time is newer than the original image).

The second part of using XMP meta data is turning it into an array(). You could parse the extracted XML, but adobe uses a variety of namespaces, which makes it difficult and tedious to code — especially since we’re probably just interested in a few values anyway.

I chose an easier method by using regular expressions to parse the XML instead. I use an associative array to describe the regular expressions, and then check the matched values for <rdf:li> XML tags to create second dimension arrays. The <lr:hierarchicalSubject> XML tag needs additional parsing to create a third dimension array from it’s pipe-delimited values.

In the case of WordPress, a usage example might look like this.

Leave a Reply

Your email address will not be published. Required fields are marked *