Putting a JSON result within []
Clash Royale CLAN TAG#URR8PPP
Putting a JSON result within
I am trying to add values from a JSON API to a MySQL. The problem is that the result return without the , so I cannot foreach it and insert all the values to the database.
This is the API URL
http://horoscope-api.herokuapp.com/horoscope/today/Gemini
This is the code I am having
$data = file_get_contents(
"https://horoscope-api.herokuapp.com/horoscope/today/Gemini",
true);
$array = json_decode($data, true); //Convert JSON String into PHP Array
foreach($array as $row) //Extract the Array Values by using Foreach Loop
$query .= "INSERT INTO zodiac(date, horoscope, sunsign, url)
VALUES (
'" . $row["date"]. "',
'" . $row["horoscope"]."',
'" . $row["sunsign"]."',
'" . $row["sunsign"]."'
); "; // Make Multiple Insert Query
If I combine $data = "[$data]"; (with and without the quotes) it prints correctly but cannot be parsed as an array. Or at least I cont know how to do it.
I have tried searching for some way to fix that and found some interesting ideas here How to convert JSON string to array but none of them seems to work.
And other way to get the result within ?
Thanks
is_array
The problem is that they haven't given me a nail, so I can't use a hammer. Why do you think you need to use a loop for this?
– iainn
Aug 8 at 16:50
@iainn, I guess it is because I do not know any other way to do it.
– lStoilov
Aug 8 at 17:07
@ficuscr, I need it in case I want to pars multiple single objects like ,, for example for 3 days horoscope.
– lStoilov
Aug 8 at 17:11
1 Answer
1
If I don't misunderstood you requirements then this should work for you. I've seen the API response, it is just returning a single result for a horoscope. Though I've just used your existing code to make it workable(which is not recommended to use), I wish you'll try with PDO instead.
<?php
$data = file_get_contents("https://horoscope-api.herokuapp.com/horoscope/today/Gemini",true);
$array = json_decode($data, true); //Convert JSON String into PHP Array
$query = '';
foreach($array as $key=>$row) //Extract the Array Values by using Foreach Loop
$query.= "INSERT INTO zodiac(date,horoscope,sunsign,url)
VALUES ('". $row["date"]."','".$row["horoscope"]."','".$row["sunsign"]."','".$row["sunsign"]."'); "; // Make Multiple Insert Query
echo $query;
?>
With PDO:
$data = file_get_contents("https://horoscope-api.herokuapp.com/horoscope/today/Gemini",true);
$array = json_decode($data, true); //Convert JSON String into PHP Array
$sql = "INSERT INTO zodiac (date, horoscope, sunsign) VALUES (:date, :horoscope, :sunsign)";
$stmt= $dpo->prepare($sql);
$stmt->execute($array);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
They are serving a single object. Not an "array" of objects. I don't understand the question. See
is_array
perhaps?– ficuscr
Aug 8 at 16:47