Related
This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
Why does this PHP code just echo "Array"?
(6 answers)
Closed 2 years ago.
I have really been struggling with outputting the content of a json data I received from a rest API response correctly. I have searched a lot and tried different ways but I noticed everyone's is always unique...below is my code..specifically of consideration is the "headers_field" it is an array with a lot of values and keys...and I want to also output these values with the keys...While the ("data") has two values with it...below is what I have tried also but I am just getting the first result from the loop while it returns ("headers_field": Array), ("box: Array")..I used Curl. Kindly look below. Thanks.
{
"data": [
{
"approved": null,
"approved_user_id": null,
"boxes": [],
"created": "2020-05-19T21",
"created_at": "2020-05-19T21",
"edited": null,
"edited_in_affiliate": null,
"edited_in_hdr": null,
"edited_in_web_app": null,
"erp_project_id": null,
"error_description": "",
"header_fields": [
{
"boxes": [],
"code": "creditor_number",
"data_type": "",
"error": "",
"feature_id": nvnnn,
"value": "hhhhh"
},
{
"boxes": [],
"code": "payment_account_number",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "order_number",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "total_amount_incl_vat",
"data_type": "",
"error": "",
"feature_id": mmm
"value": "hhh"
},
{
"approved": null,
"approved_user_id": null,
"boxes": [],
"created": "2020-05-19",
"created_at": "2020-05-19",
"edited": null,
"edited_in_affiliate": null,
"edited_in_hdr": null,
"edited_in_web_app": null,
"erp_project_id": null,
"error_description": "",
"header_fields": [
{
"boxes": [],
"code": "reference",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "payment_swift_bic",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "recipient_vat_reg_no",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "joint_payment_id",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "catalog_debitor_id",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "case_number",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "payment_account_number",
"data_type": "",
"error": "",
"value": ""
},
{
"boxes": [],
"code": "payment_iban",
"data_type": "",
"error": "",
"value": ""
}
],
"id": 00000,
"image": "https://skkkkkllllllllll
"line_items": [],
"note": "",
"organization_id": 11111,
"organization_voucher_id": 7777,
"page_count": 1,
"status": "successful",
"type": "voucher",
"upload_type": "affiliate",
"uploaded_by_user_id": 0000001
"user_payment_method": "",
"user_voucher_type": ""
}
],
"meta": {
"count": 2
}
}
MY LOOP OPERATION
.....
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$results= curl_exec($ch);
$g= json_decode($results, true);
$i=0;
$g_length =count($g["data"]);//to count through the child array
for ($i=0; $i < ($g_length);$i++)
{
$k= $g["data"][$i]; //asssigning the array position to a variable
foreach($k as $mydata=>$mvalue) {
$hey = trim($mvalue); //Removes white spaces
if ($mvalue !=="")
echo $mydata. " : " . $mvalue . "<br>";
else
echo "This is empty. <br/>";
///////////////////////////////////////////
foreach($mvalue as $lkey=>$lvalue)
{
$u=is_array($mvalue);
if(($u) and !empty($u))
echo $lkey. ":" . $lvalue. "<br>";
else
echo "what? <br/>";
///////////
foreach($lvalue as $okey=>$ovalue)
{
echo $okey. ":". $value. "</n>";
/////
foreach($ovalue as $key=>$value)
{
$v=is_array($value);
if(($v) and !empty($v))
echo $key. ":" . $value. "<br>";
else
echo "hello";
//print_r($key);
/////
}
}
//////////
}
//////////////////////////////////////////
}
Provided you know how deep the array is that you get back from the API or how many dimensions and you know the key structure will be the same you could use something like this:
NOTE: I took your JSON and did a quick and dirty to spit out all the keys and values - including the nested header fields. Essentially its based on whether the value is an ARRAY. If you know the structure you are expecting you could make this more elegant by creating an array map and a function to process all vals that are sub arrays.
Anyway - I hope the below helps you as a starter:
foreach($theDecodedData['data']["header_fields"] as $row){
foreach($row as $key => $val){
if(!is_array($val)){
echo "$key: $val \n";
}
else{
echo "Contents of $key \n";
foreach($val as $vkey => $vval){
if(!is_array($vval)){
echo "$vkey: $vval \n";
}
else{
echo "Contents of $vkey \n";
foreach($vval as $vvvkey => $vvvval){
if(!is_array($vvvval)){
echo "$vvvkey: $vvvval \n";
}
else{
echo "Contents of $vvvkey \n";
foreach($vvvval as $vvvvkey => $vvvvval){
echo "$vvvvkey: $vvvvval \n";
}
}
}
}
}
}
}
}
I'm trying to parse data returned by the Jotform API.
I'm successfully echoing the data but I'm also getting unnecessary additional lines of text.
My PHP code is:
include "JotForm.php";
$jotformAPI = new JotForm("myapikey");
$submissions = $jotformAPI->getFormSubmissions("myformid");
var_dump($submissions );
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
foreach ($detail as $d) {
echo $d[1]['answer']['first'] . '<br>';
}
}
result of var_dump($submissions );
{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}],
}
And here is the result I'm getting:
1
0
0
0
C
0
LeBron
I had to repair your invalid json string...
Code: (Demo)
$json = '{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}}]
}';
foreach (json_decode($json, true)['content'] as $set) {
echo "{$set['answers'][1]['answer']['first']} {$set['answers'][1]['answer']['last']}\n";
}
Output:
LeBron James
I'm a little fuzzy on the action of the jot functions, but maybe it's supposed to be like this:
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
echo $detail['answers'][1]['answer']['first'] . '<br>';
}
I have a json response like this:
{
"status": 200,
"msg": "OK",
"result": {
"folders": [
{
"id": "3812454",
"name": ".subtitles"
},
{
"id": "3812455",
"name": ".videothumb"
}
],
"files": [
{
"name": "Angamaly Diaries HD.MP4.mp4",
"cblock": null,
"sha1": "fcc2c99f2db6e3e8a700c3247206a1c2148e14cb",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "713544705",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "PjUv5IYA2J8"
},
{
"name": "Take Off 2017.MP4.mp4",
"cblock": null,
"sha1": "2fe7fb4d45322a085d41239d6429d1cc8e94e2ce",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "954148848",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "BIBcjWqF0_I"
},
{
"name": "Rangoon 2017 Tamil.MP4.mp4",
"cblock": null,
"sha1": "c685e7c11636982860ae7f34b671a20fc746feee",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "779899588",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "00D7GzP6mls"
},
{
"name": "The Zookeeper’s Wife 2017.MP4.mp4.mp4",
"cblock": null,
"sha1": "a143faafbd8a6eaf2276f25cd642ac3019d71ffc",
"folderid": "3812453",
"upload_at": "1510256266",
"status": "active",
"size": "550126461",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "bwUhqbiJJWQ"
}
]
}
}
And I have a string with this text:
"Watch Take Off 2017 Malayalam Full Movie Online Free"
Now I need to get the linkextid of
"name": "Take Off 2017.MP4.mp4"
from JSON response. There is one more thing that I have so much similar data on the JSON response, but I need to the get name that matches maximum words from string using PHP.
<?php
$json_data='{"status":200,"msg":"OK","result":{"folders":[{"id":"3812454","name":".subtitles"},{"id":"3812455","name":".videothumb"}],"files":[{"name":"Angamaly Diaries HD.MP4.mp4","cblock":null,"sha1":"fcc2c99f2db6e3e8a700c3247206a1c2148e14cb","folderid":"3812453","upload_at":"1510255141","status":"active","size":"713544705","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"PjUv5IYA2J8"},{"name":"Take Off 2017.MP4.mp4","cblock":null,"sha1":"2fe7fb4d45322a085d41239d6429d1cc8e94e2ce","folderid":"3812453","upload_at":"1510255141","status":"active","size":"954148848","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"BIBcjWqF0_I"},{"name":"Rangoon 2017 Tamil.MP4.mp4","cblock":null,"sha1":"c685e7c11636982860ae7f34b671a20fc746feee","folderid":"3812453","upload_at":"1510255141","status":"active","size":"779899588","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"00D7GzP6mls"},{"name":"The Zookeeper’s Wife 2017.MP4.mp4.mp4","cblock":null,"sha1":"a143faafbd8a6eaf2276f25cd642ac3019d71ffc","folderid":"3812453","upload_at":"1510256266","status":"active","size":"550126461","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"bwUhqbiJJWQ"}]}}';
$data=json_decode($json_data,true);
$files=$data['result']['files'];
$search="Watch Take Off 2017 Malayalam Full Movie Online Free";
$search_array=explode(' ',$search);
foreach($search_array as $key=>$row){
$search_array[$key]=trim($row);
}
$match=[];
foreach($files as $key=>$row){
$match_count=0;
foreach($search_array as $s){
if(preg_match('/'.$s.'/',$row['name'])){
$match_count+=1;
}
}
$match[$key]=$match_count;
}
rsort($match);
print_r($files[$match[0]]['linkextid'])
?>
Not the best solution in the world but this should work:
<?php
function compare_strings($s1, $s2) {
$s1Words = explode(' ', $s1);
$s2Words = explode(' ', $s2);
$wordCount = 0;
foreach ($s1Words as $word) {
if ( strpos($s2Words, $word) ) {
$wordCount++;
}
}
return $wordCount;
}
function get_movie_linkextid($data, $name) {
$bestMatchIndex = 1;
$bestMatchScore = 0;
foreach ($data['result']['files'] as $i => $movie) {
$currentScore = compare_strings($movie['name'], $name);
if ($currentScore > $bestMatchScore) {
$bestMatchScore = $currentScore;
$bestMatchIndex = $i;
}
}
return $data['result']['files'][$bestMatchIndex]['linkextid'];
}
$data = json_decode($yourJsonData, true);
$name = "Watch Take Off 2017 Malayalam Full Movie Online Free";
echo get_movie_linkextid($data, $name);
?>
The code just parses your JSON into a variable and than goes through all the 'files' comparing their names with the string you provided the determine the best match. After that it just return the linkextid.
I Didn't tested this code but the important is to get the idea since you will have to adapt it to be more generic anyway.
I have a TXT file containing some facebook Open Graph info like this:
{
"data": [
{
"name": "Avatar",
"category": "Movie",
"id": "82771544063",
"created_time": "2012-04-13T21:16:56+0000"
},
{
"name": "HappyDance",
"category": "Movie",
"id": "243564344063",
"created_time": "2012-04-13T21:16:56+0000"
}
],
"paging": {
"next": "https://graph.facebook.com/me/likes?format=json&limit=5000&offset=5000&__after_id=5546653546361"
}
}
In PHP, I want to extract all the id numbers from the rows that show
"id": "XXXXXXXXXXXX",
The output should look like this:
I like 8277564344063
I like 243564344063
I started the following but I am getting an error:
<?php
$file_handle = fopen("raw.txt", "rb");
ob_start();
$text = file_get_contents('raw.txt');
$decode = json_decode($text);
print_r($decode);
$new_content = ob_get_clean();
file_put_contents("likes.txt", $new_content);
fclose($file_handle);
?>
The error is that my output is blank! What am I doing wrong?
Please help?
You don't have valid JSON.
The JSON Object below this line is valid JSON. I removed the comma after your last associative array within your "data" array. You shouldn't need a comma at the end of the array.
{
"data": [
{
"name": "Avatar",
"category": "Movie",
"id": "82771544063",
"created_time": "2012-04-13T21:16:56+0000"
},
{
"name": "HappyDance",
"category": "Movie",
"id": "243564344063",
"created_time": "2012-04-13T21:16:56+0000"
}
],
"paging": {
"next": "https://graph.facebook.com/me/likes? format=json&limit=5000&offset=5000&__after_id=5546653546361"
}
}
Parse error on line 14:
... }, ], "paging": {
---------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
As I removed the comma from the non-valid JSON. I was able to get the result you wanted.
<?php
$json_object = file_get_contents('fb.json');
if(!$json_object) {
echo "oops, cant read the file";
}
// remap json_object
$json_object = json_decode($json_object,true);
foreach($json_object['data'] as $item) {
$items[] = "I like" . ' ' . $item['id'];
/* If you want to just echo " I like xyz" etc
* use echo "I like" . $item['id'];
*/
}
$list = implode(',',$items);
echo $list;
?>
I have a list of movies and I want to compare to the Array of movies i got from Facebook Graph API.
Here is an example of what API is getting:
{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}...
The list I need to compare is pretty big, but here are some:
Wall Street, Shooter, Young Guns, Due Date...
Basically just compare 'Name' in 'data' with 'my list' of Movie titles. But can't figure out the syntax
Something like:
if ($movies->data->name == 'movie titles list') {echo "You like the same movies";}
I found this:
if (in_array('movie titles list', $a)) {echo "You like the same movies";}
Any thoughts would help me out.
Thanks
The data looks to be JSON encoded...
Try something like this: (json_decode)
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}]}';
$json_to_array = json_decode($large_data, true);
var_dump(json_decode($large_data, true));
// You should now be able to compare the two array
echo print_r($json_to_array,true);
EDIT:
Improving on what #Eric posted
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}]}';
$movie_list = json_decode($large_data, true);
$movieNames = array();
foreach($movie_list as $movies) {
foreach($movies as $movie) {
$movieNames[] = $movie['name'];
}
}
$myMovies = array('Wall Street', 'Shooter', 'Young Guns', 'Due Date');
$common_movies = array_intersect($movieNames, $myMovies);
foreach($common_movies as $common_movie) {
echo "We like the same movie ".$common_movie."<br />\n";
}
Another method:
<?php
$json_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}
]}';
$array_data = json_decode($json_data, TRUE);
$compare_list = array(
'Wall Street',
'Shooter',
'Young Guns',
'Due Date'
);
// <Marco Stumper> phpundhtml at web dot de
function in_array_multi($needle, $haystack) {
$found = false;
foreach ($haystack as $value) {
if ((is_array($value) && in_array_multi($needle, $value)) || $value == $needle) {
$found = true;
}
}
return $found;
}
foreach ($compare_list as $item) {
echo '<p>' . $item . (in_array_multi($item, $array_data) ? ' DOES ' : ' does NOT ') . 'exist within $array_data</p>' . PHP_EOL;
}
?>
Output:
<p>Wall Street does NOT exist within $array_data</p>
<p>Shooter DOES exist within $array_data</p>
<p>Young Guns does NOT exist within $array_data</p>
<p>Due Date does NOT exist within $array_data</p>
Use array_intersect(array1, array2, ... arrayN)
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}
]}';
$movies = json_decode($large_data, true)['data'];
$movieNames = array();
//Get only the name from the movie list
foreach($movies as $movie) {
$movieNames[] = $movie['name'];
}
//Intersect with internal list
print_r(array_intersect($movieNames, $myMovies));