Early Bird Registration for DrupalCon Portland 2024 is open! Register by 23:59 PST on 31 March 2024, to get $100 off your ticket.
By Sheldon Rampton on
I've been poking around Drupal's XML-handling functions and don't see anything that provides simple XML-to-array conversion. To parse XML, it looks like you have to create your own parser, which means writing several functions for tag handling, etc. It would be nice to be able to do something like the following, which uses Technorati's REST API retrieve a list of blogs that link to a URL:
$request = "http://api.technorati.com/cosmos?key=$mykey&url=$url";
$result = drupal_http_request($request);
$vals = xml2array( $result->data );
$items = $vals['tapi'][0]['document'][0]['item'];
foreach ($items as $item) {
if ($item['nearestpermalink']) {
$links[] = l($item['weblog'][0]['name'], $item['nearestpermalink']);
}
Here's the xml2array function that would do the heavy lifting:
function xml2array( $textXml )
{
$regExElements = '/<(\w+)([^>]*)>(.*?)<\/\\1>/s';
$regExAttributes = '/(\w+)="([^"]*)"/';
preg_match_all( $regExElements, $textXml, $matchElements );
foreach ( $matchElements[1] as $keyElements=>$valElements ) {
if ( $matchElements[2][$keyElements] )
{
preg_match_all( $regExAttributes, $matchElements[2][$keyElements], $matchAttributes );
foreach ( $matchAttributes[0] as $keyAttributes=>$valAttributes )
{
$arrayAttributes[ $valElements.' attributes' ][$matchAttributes[1][ $keyAttributes ] ] = $matchAttributes[2][ $keyAttributes ];
}
}
else
{
$arrayAttributes = null;
}
if ( preg_match( $regExElements, $matchElements[3][$keyElements]) ) {
if ( $arrayAttributes )
{
$arrayFinal[ $valElements ][ $valElements.' attributes' ] = $arrayAttributes[ $valElements.' attributes' ];
}
$arrayFinal[ $valElements ][] = wholinks_xml2array( $matchElements[3][$keyElements] );
}
else
{
$arrayFinal[ $valElements ] = $matchElements[3][ $keyElements ];
$arrayFinal = array_merge( $arrayFinal, $arrayAttributes );
}
}
return $arrayFinal;
}
Any chance of getting this added to core, or is there already some equivalent available that I don't know about?
Comments
Yes, we need something like this
Here's a similar approach I've been looking at, cribbed (and slightly adapted) from some code in the Freja library. It handles both conversions (PHP array <> XML). Not sure what the CDATA part is about, maybe it's to avoid issues with illegal characters.
Likely XML serializing/handling will be best initially as a contrib module.
Cool
Thanks nedjo this is just what I need!
XML Parsing with SimpleXML
Another way to parse XML is to use SimpleXML.
A good demonstration performed during Barcelona DrupalCon is available here: http://drupal.org/node/178374
Better yet, try QueryPath, a
Better yet, try QueryPath, a Drupal module that is simpler to use than SimpleXML and way more powerful:
http://drupal.org/project/querypath
----------------
Customer Support Engineer, Granicus
https://granicus.com