17 Jan
VIN API – PHP and XML Parsing
Thanks go to Michael for sharing his hard work with the rest of you VIN API and PHP developers 🙂
I hope this helps -
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
// VIN API decoder for PHP 4.x+ | |
define('ELEMENT_CONTENT_ONLY', true); | |
define('ELEMENT_PRESERVE_TAGS', false); | |
function getXML($vin) { | |
$curl = curl_init(); | |
curl_setopt ($curl, CURLOPT_URL, 'http://vinapi.skizmo.com/vins/'. $vin.'.xml'); | |
curl_setopt ($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', 'X-VinApiKey: #YOURAPIKEYGOESHERE#')); //use your API key here | |
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, true); | |
$result = curl_exec ($curl); | |
curl_close ($curl); | |
return $result; | |
} | |
function parseVIN($VIN) { | |
$info = array("model", "body-style", "country", "world-region", "vin", "engine-type", "transmission", "year", "make"); //include all values you want decoded | |
$info = sort($info); //alphabetical order | |
foreach ($info AS $type) { | |
$vin[$type] = parseDATA($type, $VIN); | |
} | |
return $vin; | |
} | |
function parseDATA($element_name, $xml, $content_only = true) { | |
if ($xml == false) { | |
return false; | |
} | |
$found = preg_match('#<'.$element_name.'(?:\s+[^>]+)?>(.*?)'. | |
'</'.$element_name.'>#s', $xml, $matches); | |
if ($found != false) { | |
if ($content_only) { | |
return $matches[1]; //ignore the enclosing tags | |
} else { | |
return $matches[0]; //return the full pattern match | |
} | |
} | |
// No match found: return false. | |
return false; | |
} | |
// Parse passed VIN to remove illegal characters | |
$vin = preg_replace("/[^A-Za-z0-9.]/", "", $_GET['vin']); | |
if(isset($_GET['vin'])) { | |
$data = getXML($vin); | |
$data = parseVIN($data); | |
if ($data != false) { | |
foreach ($data AS $key => $value) { | |
echo ucfirst($key) . ": " . $value . "<br />"; | |
} // outputs each XML node available | |
} else { | |
echo "VIN did not return any data."; | |
} | |
} | |
?> |