After googling, implementing code upon code, I still cannot get ANYTHING to display. Nothing. Not one thing.
I have a URL spitting out JSON:
{"videos":[{"video":{"name":"Sanyo Zio","youtube":"FxxLDr--R5A","post_date":"2010-10-08 01:00:00",...
Here's the code I'm using to access the page:
$url = file_get_contents("http://[website]/json/test.json");
$arr = json_decode($url,true);
Now here's a short list of what I've tried to access ANY data from the page:
1:
print_r($arr);
2:
foreach($arr['videos']['video'] as $item) {
echo "Name: ". $item[0] ."<br>";
}
3:
$obj = $arr[0];
echo $obj;
4:
foreach($arr as $a){
echo "Name: ".$a['videos']['video']['name']."<br />";
}
Clearly I'm missing something, but I just haven't been able to figure out what I'm doing wrong! Is my encoding not correct? Here's how I'm encoding the JSON to begin with:
$arr = array('videos' => array());
foreach($vid as $items){
$arr['videos'][] = array('video' => array(
'name' => $items['videoName'], 'youtube' => $items['youtubeID'], 'post_date' => $items['productionTimestamp'], 'description' => $items['videoDesc'], 'link' => $single_linker_values['deeplink'], 'image' => $image));
}
echo json_encode($arr);
Any ideas/suggestions?
Update - Apparently the server is locked down, but being inhouse I don't notice :) Obviously the webpage does! Thanks for the help!
From PHP Manual
NULL is returned if the json cannot be decoded or if the encoded data
is deeper than the recursion limit
Since you are not specifying a recursion limit, chances are that either your JSON is invalid or nothing is being retrieved from your URL.
Three things to try:
determine if there was a json_decode error
print_r(json_last_error()); // call after json_decode
check that data is being returned
print_r($url);
see if data will decode as an object
$obj = json_decode($url);
print_r($obj);
Related
I have data in Json format which i have decoded into a php array which when printed produces the following (just a snippet of the information).
Array (
[Title] => Array([Heading] => Company Name [Info] =>)
[SubTitle] => Array([Heading] => Welcome to Company Name[Info] =>information on the company)
)
my question is how do I loop through this information and print the title and then print the value.
I have tried the following which prints all the data at one time
foreach($data['SubTitle'] as $key => $value){
echo $value;
}
And then i tried this just to print the info section which i thought might work but instead throws an illegal string offset error
foreach($data['SubTitle'] as $key => $v){
echo $v['Info'];
}
I can get the information from the Title array as it is straight forward as it only has data value in the heading. However i would like the output from the Subtitle array to print the heading and info like below:
Welcome to Company Name
Information on the company
I thought this would be straight forward but it is turning out much more difficult than expected and has taken up a lot of time so any help would be greatly appreciated.
So I am going to assume you have a JSON string that looks like this:
$json = '{"Title":{"Heading": "Company Name", "Info": null}, "SubTitle": {"Heading": "Welcome to Company Name", "Info": "information on the company"}}';
visualised, looks something like this:
So, if you've decoded this json into an associative array:
$result = json_decode($json, true);
Then, in order to access the data, you don't need to "loop" over it; all you need to do is:
echo $result['Title']['Heading']; // will print 'Company Name'
echo $result['Title']['Info']; // will print nothing, as it is empty
echo $result['SubTitle']['Heading']; // will print 'Welcome to Company Name'
echo $result['SubTitle']['Info']; // will print 'information on the company'
Hope this helps. This is basic php, please look into the following reading materials:
https://www.php.net/manual/en/function.json-decode.php
https://www.w3schools.com/php/php_arrays.asp
Change your code, from this:
foreach($data['SubTitle'] as $key => $v){
echo $v['Info'];
}
To this:
foreach($data['SubTitle'] as $v){
echo $v . "<br/>"; // the <br/> makes a new line
}
Output will be:
Welcome to Company Name
Information on the company
$v is no longer an array in foreach, it becomes a variable.
Some information about html tags: https://www.w3schools.com/tags/
Also see how loop works: https://www.guru99.com/php-loop.html
I wanted to try something out with an API from a company. I wanted to put their data into my database. But I've run into a problem. The API has one JSON object called "venue.country". But I can't use dots in my array for some reason?
Here is the code:
foreach ($data[1]['hits']['hits'] as $row) {
$statement->execute(array(
"name" => $row['fields']['name'][0],
"date" => $row['fields']['start'][0],
"lang_long" => "test",
It is this one! -> "country" => $row['fields']['venue.country'][0],
"genres" => $row['fields']['genres'][0],
"desc" => $row['fields']['description'][0],
"logo" => $row['fields']['logo'][0],
"header_pic" => $row['fields']['header'][0]
));
}
\everything else works in the PHP
And here is a piece of the JSON:
venue.country: [
"Nederland"
],
How can I get this to work? Can I use the "explode" method?
This is the full JSON:
https://hugo.events/genre/pop/next/200/120
Thanks.
EDIT:
Even with the answer #Prototype Chain gave it is giving me this error: Notice: Undefined index: venue in /home/ubuntu/workspace/pop.php on line 18
This code works just fine given your example JSON data:
$string = <<<EOT
{INSERT YOUR JSON STRING HERE}
EOT;
$json = json_decode( $string, true );
echo $json[1]['hits']['hits'][0]['fields']['venue.location'][0] . "\n";
echo $json[1]['hits']['hits'][0]['fields']['venue.location'][1] . "\n";
The code works fine. After debugging I found that, there is no key/index venue.country for the array elements $data[1]['hits']['hits'][50] and $data[1]['hits']['hits'][51]. Since there is no index, its throwing notice.
You can add #before the variable to suppress the notice or check the condition if the index exixts.
"country" => #$row['fields']['venue.country'][0],
"country" => isset($row['fields']['venue.country']) ? $row['fields']['venue.country'][0] : '',
// run this code for testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
$jsondata = file_get_contents('https://hugo.events/genre/pop/next/200/100');
$data = json_decode($jsondata, true);
foreach ($data[1]['hits']['hits'] as $row) {
// echo $row['fields']['name'][0].'=>'.#$row['fields']['venue.country'][0].'<br/>';
$array[]= array(
"name" => $row['fields']['name'][0],
"country" => isset($row['fields']['venue.country']) ? $row['fields']['venue.country'][0] : ''
);
}
echo "<pre>";
print_r($array);
It's a little hard to debug without seeing the entire contents of the JSON data, however, in the past when I've hard trouble parsing JSON or XML data from a source that formatted it strangely, I found it useful to perform a pre-process str_replace() on the data before I parsed it.
So something like this might work for you:
$input = some_function_to_get_string_data_from_api();
$input = str_replace( "venue.country", "venuecountry", $input );
$json = json_encode( $input );
It's not an elegant solution, and it falls apart quickly if you're dealing with lots and lots of fields that need modifying, but if you're only dealing with a single field or two that are giving you trouble, it can be a quick and dirty patch.
Hope this will do the trick..
$row['fields']['venue']['country'][0]
im using a text messaging service provider to send and receive messages. the following is the code that works successfully to retrieve messages from the texting server and displays on my website
the problem is when it displays this data its in one big chunk,sorry im not a great programmer therfore I want to split each text messages up by a few spaces,
please could you help me write up a json script that would allow me to split up my result, cheers
You need to decode the JSON from the string into an array or object, using json_decode() it has a second parameter that's bool (When TRUE, returned objects will be converted into associative arrays.)
So something like (Object):
$responseObj = json_decode($response);
foreach ( $responseObj as $key => $value )
echo "$key = $value<br>";
So something like (Array):
$responseArray = json_decode($response, true);
foreach ( $responseArray as $key => $value )
echo "$key = $value<br>";
first of all do use json_decode function of php then it will come up in an array where at "messages" index you can find your all messages. After that you have to run for each loop then you can get your code working.
$arr = json_decode($response, true);
foreach($arr['messages'] as $message){
echo $message['message'];
}
<?php
$response = json_decode($response);
foreach($response['messages'] as $msgObj) {
print $msgObj->message . "<br/><br/>";
}
?>
I have the following in myfile.php
$json_data = '{"type":"email","msg":"some text"}';
Instead of typing "email" or "some text" I want to concat the php variables $thetype and $themsg to the line before.
How can I do that? No matter what I do I get a syntax error.
I'm trying:
$json_data = '{"type":"+$thetype+","msg":"+$themsg+"}';
But as I say errors galore.
Thanks a lot
Your question is a little vague...
Are you looking for this?
$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);
That will set $json_data to a string like what you described:
<?php
$thetype = 'something';
$themsg = 'something else';
$json = array('type' => $thetype, 'msg' => $themsg);
$json_data = json_encode($json);
var_dump($json_data);
Would print:
string(43) "{"type":"something","msg":"something else"}"
See the PHP manual for json_encode.
You could try and build the string by hand, like this:
$json_data = '{"type":"'. addcslashes($thetype,"\"'\n").'","msg":"'. addcslashes($themsg,"\"'\n").'"}';
But, you'll generally be better off using json_encode, as it's designed for this purpose and is much less likely to produce invalid JSON.
PHP has a function to encode json.
HOWEVER you need to output it as an object to save the keys.
This is a 3D array by the way.
$data[]=array('type' => $thetype0, 'msg' => $themsg0);
$data[]=array('type' => $thetype1, 'msg' => $themsg1);
$json=json_encode((object)$data);
EDIT: This method should be used for OLDER PHP versions. It is compatible with PHP 5.3.
The json_encode() function has several changes to it that makes it so the object output isnt available in PHP 5.2.
EDIT
Solved it. It was before the ajax call and, hence, this code. Thank you all for the answers.
I can't find anybody with this problem. I have a AJAX call to a PHP script that returns a JSON response.
I fetch the values from a database into an array:
while($row = mysql_fetch_array($ret)){
$temp = array(
'id' => $row['id_reserva'],
'start' => $row['data_inicio'],
'end' => $row['data_fim'],
'title' => $row['descricao']
);
$js[] = $temp;
}
Headers:
header('Content-type: application/json');
And echo:
echo json_encode($js);
There is no return whatsoever, just a null string.
What is really bugging me is that if instead of this I create a json string with the previous result directly in the code:
$temp = '[{"id":"3914", "start": "2011-08-25 09:00:00",
"end":"2011-08-25 18:00:00", "title":"asdasdasd"},
{"id":"3915", "start": "2011-08-25 09:00:00",
"end":"2011-08-25 18:00:00", "title":"asdasdasd"}]';
echo $temp;
It works.
Tried changing the file codification, comparing the strings, checking for some problem with chars, and nothing.
Anybody?
Cheers
you have to encode it. try
echo json_encode($js);
You need to json encode array:
echo json_encode($js);
You're not outputting as JSON?
echo json_encode($js);
With your method, when jQuery gets the response and cannot parse the JSON it will return the empty string as you have experienced.
Process of elimination..
can you print_r ($js) and get output?
Take out the header(); statement, does anything appear?
Do you have error_reporting and display_errors turned on?
You don't seem to initializing 'js' ($js = array()). If you get the literal string 'null' back, this could simply imply that your query is not returning any results.
I could add this statement to almost every long-winded PHP requestion on stack overflow:
Go through your code step by step and echo what you expect the contents of variables to be at that point. Then you'll slowly isolate exactly where your issue is; there's nothing wrong with your code as-is.
Are you not making a multi-dimentional array with $js[] = $temp; and then encoding that? Try just doing json_encode($temp);