Php array to json encode not working












2















I have a ajax connection to my json.php file and its not working... do you have any idea what is going on?
is it my $output variable is it not convertible to json can it be my ajax?!
any help will be greatly appreciated. PS: when i click on a city that does not exist.. it does output the $output variable.When i click on a city that doe exist I get nothing.
It`s killing me.
var_dump($output) {if it is not encoded} is:



    array (size=1)
0 =>
array (size=4)
0 =>
object(SimpleXMLElement)[9]
1 =>
object(SimpleXMLElement)[8]
2 =>
object(SimpleXMLElement)[7]
3 =>
object(SimpleXMLElement)[10]


json.php file:



<?php

if(isset($_POST['city'])){
$city = $_POST['city']; //checks if variable city is set if not it will be set as default
var_dump($city);
}else{
$city = 'New York';


}
//loads data as simple xml
$result = "http://api.wunderground.com/api/KEY/geolookup/conditions/q/ro/$city.xml";
$xml = simplexml_load_file($result);
#echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$place = $xml->location->city; //gets the city name
#var_dump($place);
if(!empty($place)){ //checks if city exits
foreach($xml->current_observation as $item){
$current = (string)$item->weather;
$temperature = (string)$item->temp_c;
$time = (string)$item->local_time_rfc822;
$wind = (string)$item->wind_string;
$humidity = (string)$item->relative_humidity;
$output = array($time, $temperature, $current, $wind);

}

}
}else{
$output = 'No results found, please try a different city.'; //if variable $place is empty it will print this
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('data' => $output),true);
?>


And jQuery file:



 $(document).ready(function() {
$('li').click(function(){
var city = $(this).text(); //get the li content as variable city
$.ajax({

type : 'POST', //sending data method
url : 'json.php',
data : {city:city}, //data to be sent
dataType: 'json',
success : function(data){
$("#result").html(data);
}
});

});
});


EDIT 1:
I have updated my code in such a way that my output is json encoded and equal to



{"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}


I think the problem now is in my AJAX(I am a new user of jQuery) I get no info printed when I Click on a city.










share|improve this question




















  • 7





    You don't have just a multidimensional array... you have an array full of SimpleXML objects. I don't think json_encode will know how to properly convert those so you'll need to do the conversion to a stdClass object or array.

    – Devon
    Sep 23 '15 at 20:45











  • i found a simpler way to do what you said and it`s still not working.I think the problem could be my noobie AJAX.Now my php output encoded in json is: {"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}

    – AleXzpm
    Sep 23 '15 at 23:08


















2















I have a ajax connection to my json.php file and its not working... do you have any idea what is going on?
is it my $output variable is it not convertible to json can it be my ajax?!
any help will be greatly appreciated. PS: when i click on a city that does not exist.. it does output the $output variable.When i click on a city that doe exist I get nothing.
It`s killing me.
var_dump($output) {if it is not encoded} is:



    array (size=1)
0 =>
array (size=4)
0 =>
object(SimpleXMLElement)[9]
1 =>
object(SimpleXMLElement)[8]
2 =>
object(SimpleXMLElement)[7]
3 =>
object(SimpleXMLElement)[10]


json.php file:



<?php

if(isset($_POST['city'])){
$city = $_POST['city']; //checks if variable city is set if not it will be set as default
var_dump($city);
}else{
$city = 'New York';


}
//loads data as simple xml
$result = "http://api.wunderground.com/api/KEY/geolookup/conditions/q/ro/$city.xml";
$xml = simplexml_load_file($result);
#echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$place = $xml->location->city; //gets the city name
#var_dump($place);
if(!empty($place)){ //checks if city exits
foreach($xml->current_observation as $item){
$current = (string)$item->weather;
$temperature = (string)$item->temp_c;
$time = (string)$item->local_time_rfc822;
$wind = (string)$item->wind_string;
$humidity = (string)$item->relative_humidity;
$output = array($time, $temperature, $current, $wind);

}

}
}else{
$output = 'No results found, please try a different city.'; //if variable $place is empty it will print this
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('data' => $output),true);
?>


And jQuery file:



 $(document).ready(function() {
$('li').click(function(){
var city = $(this).text(); //get the li content as variable city
$.ajax({

type : 'POST', //sending data method
url : 'json.php',
data : {city:city}, //data to be sent
dataType: 'json',
success : function(data){
$("#result").html(data);
}
});

});
});


EDIT 1:
I have updated my code in such a way that my output is json encoded and equal to



{"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}


I think the problem now is in my AJAX(I am a new user of jQuery) I get no info printed when I Click on a city.










share|improve this question




















  • 7





    You don't have just a multidimensional array... you have an array full of SimpleXML objects. I don't think json_encode will know how to properly convert those so you'll need to do the conversion to a stdClass object or array.

    – Devon
    Sep 23 '15 at 20:45











  • i found a simpler way to do what you said and it`s still not working.I think the problem could be my noobie AJAX.Now my php output encoded in json is: {"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}

    – AleXzpm
    Sep 23 '15 at 23:08
















2












2








2


0






I have a ajax connection to my json.php file and its not working... do you have any idea what is going on?
is it my $output variable is it not convertible to json can it be my ajax?!
any help will be greatly appreciated. PS: when i click on a city that does not exist.. it does output the $output variable.When i click on a city that doe exist I get nothing.
It`s killing me.
var_dump($output) {if it is not encoded} is:



    array (size=1)
0 =>
array (size=4)
0 =>
object(SimpleXMLElement)[9]
1 =>
object(SimpleXMLElement)[8]
2 =>
object(SimpleXMLElement)[7]
3 =>
object(SimpleXMLElement)[10]


json.php file:



<?php

if(isset($_POST['city'])){
$city = $_POST['city']; //checks if variable city is set if not it will be set as default
var_dump($city);
}else{
$city = 'New York';


}
//loads data as simple xml
$result = "http://api.wunderground.com/api/KEY/geolookup/conditions/q/ro/$city.xml";
$xml = simplexml_load_file($result);
#echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$place = $xml->location->city; //gets the city name
#var_dump($place);
if(!empty($place)){ //checks if city exits
foreach($xml->current_observation as $item){
$current = (string)$item->weather;
$temperature = (string)$item->temp_c;
$time = (string)$item->local_time_rfc822;
$wind = (string)$item->wind_string;
$humidity = (string)$item->relative_humidity;
$output = array($time, $temperature, $current, $wind);

}

}
}else{
$output = 'No results found, please try a different city.'; //if variable $place is empty it will print this
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('data' => $output),true);
?>


And jQuery file:



 $(document).ready(function() {
$('li').click(function(){
var city = $(this).text(); //get the li content as variable city
$.ajax({

type : 'POST', //sending data method
url : 'json.php',
data : {city:city}, //data to be sent
dataType: 'json',
success : function(data){
$("#result").html(data);
}
});

});
});


EDIT 1:
I have updated my code in such a way that my output is json encoded and equal to



{"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}


I think the problem now is in my AJAX(I am a new user of jQuery) I get no info printed when I Click on a city.










share|improve this question
















I have a ajax connection to my json.php file and its not working... do you have any idea what is going on?
is it my $output variable is it not convertible to json can it be my ajax?!
any help will be greatly appreciated. PS: when i click on a city that does not exist.. it does output the $output variable.When i click on a city that doe exist I get nothing.
It`s killing me.
var_dump($output) {if it is not encoded} is:



    array (size=1)
0 =>
array (size=4)
0 =>
object(SimpleXMLElement)[9]
1 =>
object(SimpleXMLElement)[8]
2 =>
object(SimpleXMLElement)[7]
3 =>
object(SimpleXMLElement)[10]


json.php file:



<?php

if(isset($_POST['city'])){
$city = $_POST['city']; //checks if variable city is set if not it will be set as default
var_dump($city);
}else{
$city = 'New York';


}
//loads data as simple xml
$result = "http://api.wunderground.com/api/KEY/geolookup/conditions/q/ro/$city.xml";
$xml = simplexml_load_file($result);
#echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$place = $xml->location->city; //gets the city name
#var_dump($place);
if(!empty($place)){ //checks if city exits
foreach($xml->current_observation as $item){
$current = (string)$item->weather;
$temperature = (string)$item->temp_c;
$time = (string)$item->local_time_rfc822;
$wind = (string)$item->wind_string;
$humidity = (string)$item->relative_humidity;
$output = array($time, $temperature, $current, $wind);

}

}
}else{
$output = 'No results found, please try a different city.'; //if variable $place is empty it will print this
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('data' => $output),true);
?>


And jQuery file:



 $(document).ready(function() {
$('li').click(function(){
var city = $(this).text(); //get the li content as variable city
$.ajax({

type : 'POST', //sending data method
url : 'json.php',
data : {city:city}, //data to be sent
dataType: 'json',
success : function(data){
$("#result").html(data);
}
});

});
});


EDIT 1:
I have updated my code in such a way that my output is json encoded and equal to



{"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}


I think the problem now is in my AJAX(I am a new user of jQuery) I get no info printed when I Click on a city.







php jquery json ajax xml






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 23 '15 at 23:08







AleXzpm

















asked Sep 23 '15 at 20:41









AleXzpmAleXzpm

154215




154215








  • 7





    You don't have just a multidimensional array... you have an array full of SimpleXML objects. I don't think json_encode will know how to properly convert those so you'll need to do the conversion to a stdClass object or array.

    – Devon
    Sep 23 '15 at 20:45











  • i found a simpler way to do what you said and it`s still not working.I think the problem could be my noobie AJAX.Now my php output encoded in json is: {"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}

    – AleXzpm
    Sep 23 '15 at 23:08
















  • 7





    You don't have just a multidimensional array... you have an array full of SimpleXML objects. I don't think json_encode will know how to properly convert those so you'll need to do the conversion to a stdClass object or array.

    – Devon
    Sep 23 '15 at 20:45











  • i found a simpler way to do what you said and it`s still not working.I think the problem could be my noobie AJAX.Now my php output encoded in json is: {"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}

    – AleXzpm
    Sep 23 '15 at 23:08










7




7





You don't have just a multidimensional array... you have an array full of SimpleXML objects. I don't think json_encode will know how to properly convert those so you'll need to do the conversion to a stdClass object or array.

– Devon
Sep 23 '15 at 20:45





You don't have just a multidimensional array... you have an array full of SimpleXML objects. I don't think json_encode will know how to properly convert those so you'll need to do the conversion to a stdClass object or array.

– Devon
Sep 23 '15 at 20:45













i found a simpler way to do what you said and it`s still not working.I think the problem could be my noobie AJAX.Now my php output encoded in json is: {"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}

– AleXzpm
Sep 23 '15 at 23:08







i found a simpler way to do what you said and it`s still not working.I think the problem could be my noobie AJAX.Now my php output encoded in json is: {"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}

– AleXzpm
Sep 23 '15 at 23:08














2 Answers
2






active

oldest

votes


















0














Many Times it occurs when our content of the array is not Encoded. Generally we use UTF-8 Encoding.



So, To Solve this issue you need to add this,



mysqli_set_charset($con, 'utf8');



Just after the connection.






share|improve this answer































    -2














    Take a look at the following tutorial: https://lostechies.com/seanbiefeld/2011/10/21/simple-xml-to-json-with-php/



    You'll do str_replace and trim then encode the data for the web.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32749091%2fphp-array-to-json-encode-not-working%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      Many Times it occurs when our content of the array is not Encoded. Generally we use UTF-8 Encoding.



      So, To Solve this issue you need to add this,



      mysqli_set_charset($con, 'utf8');



      Just after the connection.






      share|improve this answer




























        0














        Many Times it occurs when our content of the array is not Encoded. Generally we use UTF-8 Encoding.



        So, To Solve this issue you need to add this,



        mysqli_set_charset($con, 'utf8');



        Just after the connection.






        share|improve this answer


























          0












          0








          0







          Many Times it occurs when our content of the array is not Encoded. Generally we use UTF-8 Encoding.



          So, To Solve this issue you need to add this,



          mysqli_set_charset($con, 'utf8');



          Just after the connection.






          share|improve this answer













          Many Times it occurs when our content of the array is not Encoded. Generally we use UTF-8 Encoding.



          So, To Solve this issue you need to add this,



          mysqli_set_charset($con, 'utf8');



          Just after the connection.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 '18 at 6:41









          Dharmesh PatelDharmesh Patel

          12




          12

























              -2














              Take a look at the following tutorial: https://lostechies.com/seanbiefeld/2011/10/21/simple-xml-to-json-with-php/



              You'll do str_replace and trim then encode the data for the web.






              share|improve this answer




























                -2














                Take a look at the following tutorial: https://lostechies.com/seanbiefeld/2011/10/21/simple-xml-to-json-with-php/



                You'll do str_replace and trim then encode the data for the web.






                share|improve this answer


























                  -2












                  -2








                  -2







                  Take a look at the following tutorial: https://lostechies.com/seanbiefeld/2011/10/21/simple-xml-to-json-with-php/



                  You'll do str_replace and trim then encode the data for the web.






                  share|improve this answer













                  Take a look at the following tutorial: https://lostechies.com/seanbiefeld/2011/10/21/simple-xml-to-json-with-php/



                  You'll do str_replace and trim then encode the data for the web.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 23 '15 at 23:16









                  PaulELIPaulELI

                  331413




                  331413






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32749091%2fphp-array-to-json-encode-not-working%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Costa Masnaga

                      Fotorealismo

                      Sidney Franklin