I am new to API integration and PHP. I recently integrated a VIN decoder into my app. Enter a vehicle's VIN into the input box, click submit, and information regarding the vehicle is returned.
I have been working on formatting the data output to my liking. Specifically the vehicle Make data. The Make data is presented in all-caps. For example, Audi is outputted as AUDI. To fix this I added the following code:
$data = array();
foreach ($json['Results'][0] as $k => $v){
if ($k == "Make"){
$v = strtolower($v);
$v = ucwords($v);
}
}
With this revision, AUDI is presented as Audi, which is great. I am running into issues with brands such as BMW and Mercedes-Benz. With this addition, they are presented as Bmw and Mercedes-benz. I have tried to add simple if statements to solve this but I have been unsuccessful.
Any ideas as to how I can create exceptions to the upper-case rule I created?
Here is my html code, a simple input box and submit button.
<!DOCTYPE html>
<html>
<head>
<title>VIN Decoder API Test</title>
<style type="text/css">
input,button {width: 200px;display: block;margin-left: auto;margin-right: auto;}
button {width: 100px;background-color: darkgray;}
</style>
</head>
<body>
<form action="processvin4.php" method="post">
<input type="text" id="b12" placeholder="Enter VIN" name="b12" maxlength="100"/>
<br>
<button id="submit_btn">Submit</button>
</form>
<br>
<br>
</body>
</html>
And my php code with attempted if statements:
<?php
$vin = $_POST["b12"];
if ($vin) {
$postdata = http_build_query([
'format' => 'json',
'data' => $vin
]
);
$opts = [
'http' => [
'method' => 'POST',
'content' => $postdata
]
];
$apiURL = "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/";
$context = stream_context_create($opts);
$fp = fopen($apiURL, 'rb', false, $context);
$line_of_text = fgets($fp);
$json = json_decode($line_of_text, true);
fclose($fp);
$data = array();
foreach ($json['Results'][0] as $k => $v){
if ($k == "Make"){
$v = strtolower($v);
$v = ucwords($v);
if ($v == "BMW"){
$v = "BMW";
}
if ($v == "MERCEDES-BENZ"){
$v = "Mercedes-Benz";
}
}
if (!empty($v)) {
$data[$k] = ($k).": ".($v);
}
}
echo $data['Make']. '<br />';
}
else {
echo 'No Vin Inputted';
}
?>
Thanks for any help!
To simply fix what you're trying, you just need to put the strtolower
in an "else"
if ($k == "Make"){
if ($v == "BMW"){
$v = "BMW";
}
else if ($v == "MERCEDES-BENZ"){
$v = "Mercedes-Benz";
}
else {
$v = strtolower($v);
$v = ucwords($v);
}
}