Search code examples
phpmetadatajpegxmp

How can I read XMP data from a JPG with PHP?


PHP has built in support for reading EXIF and IPTC metadata, but I can't find any way to read XMP?


Solution

  • XMP data is literally embedded into the image file so can extract it with PHP's string-functions from the image file itself.

    The following demonstrates this procedure (I'm using SimpleXML but every other XML API or even simple and clever string parsing may give you equal results):

    $content = file_get_contents($image);
    $xmp_data_start = strpos($content, '<x:xmpmeta');
    $xmp_data_end   = strpos($content, '</x:xmpmeta>');
    $xmp_length     = $xmp_data_end - $xmp_data_start;
    $xmp_data       = substr($content, $xmp_data_start, $xmp_length + 12);
    $xmp            = simplexml_load_string($xmp_data);
    

    Just two remarks:

    • XMP makes heavy use of XML namespaces, so you'll have to keep an eye on that when parsing the XMP data with some XML tools.
    • considering the possible size of image files, you'll perhaps not be able to use file_get_contents() as this function loads the whole image into memory. Using fopen() to open a file stream resource and checking chunks of data for the key-sequences <x:xmpmeta and </x:xmpmeta> will significantly reduce the memory footprint.