-3

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

alo Malbarez
  • 358
  • 2
  • 6
  • 16
lStoilov
  • 1,256
  • 3
  • 14
  • 30
  • They are serving a single object. Not an "array" of objects. I don't understand the question. See [`is_array`](http://php.net/manual/en/function.is-array.php) perhaps? – ficuscr Aug 08 '18 at 16:47
  • *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 08 '18 at 16:50
  • @iainn, I guess it is because I do not know any other way to do it. – lStoilov Aug 08 '18 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 08 '18 at 17:11

1 Answers1

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);
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103