PHP - Trying To Echo Data 3 Levels Deep Into Json Architecture
good evening folks, i have a question regarding the foreach syntax when needing to access something say 3 levels deep into the json architecture here's the example I'm trying to accomplish but when echoing it's not returning the value i need from 3 levels deep. I believe i just don't understand the correct syntax so here's the example any help would he sincerely appreciated.
https://pastebin.com/mEBiMUW5 Similar TutorialsI want to print data from response json? I was debug with firebug and show this :
{"umumu":"","levelu":1,"nameu":""}How to echo data array just levelu. But i don't know how to make it? thanks Hello everyone. I'm a self learner that is very new to programming. I'm trying to print out the value of ["mid"] from a json_decode variable in the code shown below: I'm trying to use for each to access the value of "mid'. using foreach function. I know I'm not doing it the right way. please help me or show me an easy was to go around it. /////the json resopnd form the url is : {"terms":"http://www.xe.com/legal/dfs.php","privacy":"http://www.xe.com/privacy.php","from":"USD","amount":1.195,"timestamp":"2021-02-09T16:52:00Z","to":[{"quotecurrency":"NGN","mid":454.6559871014}]} ///////////////////////////////////////////////// <?php $auth = base64_encode("username:password"); $context = stream_context_create([ "http" => [ "header" => "Authorization: Basic $auth" ] ]); $homepage = file_get_contents("https://xecdapi.xe.com/v1/convert_from?to=NGN&amount=1.195", false, $context ); $json = json_decode($homepage, TRUE); foreach ($json as $price){ echo $price['mid']; }; ?>
Hi All, I'm trying to echo the response from an SLA query, the query works and returns the data when I test it on an SQL application.. but when I run it on my webpage it won't echo the result. Please help? <?php $mysqli = mysqli_connect("removed", "removed", "removed", "removed"); $sql = "SELECT posts.message FROM posts INNER JOIN threads ON posts.pid=threads.firstpost WHERE threads.firstpost='1'"; $result = mysqli_query($mysqli, $sql); echo {$result['message']}; ?> Hi, Anybody can help me to extract data from son using php
{"location":{"woeid":2293962,"city":"Kasaragod","region":" KL","country":"India","lat":12.5174,"long":74.990662,"timezone_id":"Asia/Kolkata"},"current_observation":{"wind":{"chill":80,"direction":338,"speed":11.81},"atmosphere":{"humidity":70,"visibility":10.0,"pressure":29.8,"rising":0},"astronomy":{"sunrise":"6:54 am","sunset":"6:35 pm"},"condition":{"text":"Clear","code":31,"temperature":80},"pubDate":1549638000},"forecasts":[{"day":"Fri","date":1549564200,"low":76,"high":85,"text":"Sunny","code":32},{"day":"Sat","date":1549650600,"low":76,"high":85,"text":"Sunny","code":32},{"day":"Sun","date":1549737000,"low":75,"high":85,"text":"Sunny","code":32},{"day":"Mon","date":1549823400,"low":76,"high":87,"text":"Mostly Sunny","code":34},{"day":"Tue","date":1549909800,"low":76,"high":89,"text":"Sunny","code":32},{"day":"Wed","date":1549996200,"low":77,"high":88,"text":"Partly Cloudy","code":30},{"day":"Thu","date":1550082600,"low":76,"high":89,"text":"Mostly Sunny","code":34},{"day":"Fri","date":1550169000,"low":76,"high":86,"text":"Sunny","code":32},{"day":"Sat","date":1550255400,"low":76,"high":85,"text":"Sunny","code":32},{"day":"Sun","date":1550341800,"low":74,"high":85,"text":"Sunny","code":32}]}
How to extract data of "current_observation"
Thanks I am also trying to extract the "address_components" from the JSON data, but the array index changes if you do not submit an address line for example. I am trying to get the "sublocality" and "administrative_area_level_1" from the "address_components" below. The API sample is as follows: { "results" : [ { "access_points" : [], "address_components" : [ { "long_name" : "10", "short_name" : "10", "types" : [ "street_number" ] }, { "long_name" : "Gillespie Street", "short_name" : "Gillespie St", "types" : [ "route" ] }, { "long_name" : "South Beach", "short_name" : "South Beach", "types" : [ "political", "sublocality", "sublocality_level_1" ] }, { "long_name" : "Durban", "short_name" : "Durban", "types" : [ "locality", "political" ] }, { "long_name" : "Durban Metro", "short_name" : "Durban Metro", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "KwaZulu-Natal", "short_name" : "KZN", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "South Africa", "short_name" : "ZA", "types" : [ "country", "political" ] }, { "long_name" : "4001", "short_name" : "4001", "types" : [ "postal_code" ] } ], "formatted_address" : "10 Gillespie St, South Beach, Durban, 4001, South Africa", "geometry" : { "location" : { "lat" : -29.859728, "lng" : 31.039773 }, "location_type" : "ROOFTOP", "viewport" : { "northeast" : { "lat" : -29.8583790197085, "lng" : 31.0411219802915 }, "southwest" : { "lat" : -29.8610769802915, "lng" : 31.0384240197085 } } }, "place_id" : "ChIJGRCdW0mo9x4RcIwU_7S1xa8", "plus_code" : { "compound_code" : "42RQ+4W Durban, South Africa", "global_code" : "5G2H42RQ+4W" }, "types" : [ "street_address" ] } ], "status" : "OK" } If you submit a full address to the API, you can use the hard coded index like below: [7] $json_a['results'][0]['address_components'][7]['long_name'] But it is not reliable to hard code the index [7] in this case. So I tested some sample code from above post, it is working, but in some cases it does not return the "long_name" of the "sublocality" or "administrative_admin_level_1": /* if no address, then the array index change */ // $json_a['results'][0]['address_components'][7]['long_name'] $area = array(); foreach ($json_a['results'][0]['address_components'] as $addrObj) { foreach($addrObj['types'] as $type) { if (substr_count($type, 'sublocality')>0) { $area['short_name'] = $addrObj['short_name']; $area['long_name'] = $addObj['long_name']; // var_dump($addrObj); } if (substr_count($type, 'administrative_area_level_1')>0) { $area['short_admin'] = $addrObj['short_name']; $area['long_admin'] = $addObj['long_name']; var_dump($addrObj); } } } In the var_dump() I do get the long_name value though: In this sample it must be "Kwazulu-Natal", but from the code above, it returns a NULL value. array(3) { ["long_name"]=> string(13) "KwaZulu-Natal" ["short_name"]=> string(3) "KZN" ["types"]=> array(2) { [0]=> string(27) "administrative_area_level_1" [1]=> string(9) "political" } } Below is the full script I am trying to get to work. The lon, lng and format name is working 100%, it is just this array index problem. /* get google result in JSON*/ $googleString = file_get_contents($googleUrl); // get json content $json_a = json_decode($googleString, true); //json decoder // response status will be 'OK', if able to geocode given address if($json_a['status']=='OK'){ // get the important data $lati = isset($json_a['results'][0]['geometry']['location']['lat']) ? $json_a['results'][0]['geometry']['location']['lat'] : ""; $longi = isset($json_a['results'][0]['geometry']['location']['lng']) ? $json_a['results'][0]['geometry']['location']['lng'] : ""; $formatted_address = isset($json_a['results'][0]['formatted_address']) ? $json_a['results'][0]['formatted_address'] : ""; /* if no address, then the array index change */ // $json_a['results'][0]['address_components'][7]['long_name'] $area = array(); foreach ($json_a['results'][0]['address_components'] as $addrObj) { foreach($addrObj['types'] as $type) { if (substr_count($type, 'sublocality')>0) { $area['short_name'] = $addrObj['short_name']; $area['long_name'] = $addObj['long_name']; // var_dump($addrObj); } if (substr_count($type, 'administrative_area_level_1')>0) { $area['short_admin'] = $addrObj['short_name']; $area['long_admin'] = $addObj['long_name']; var_dump($addrObj); } } } Is there a better way to get the "sublocality" and "administrative_area_level_1" from the array $area array above. Any pointers will be much appreciated. I am retrieving Google Books info in JSON format and displaying it inside a div. I would like to send the contents of this div (name, title, description) to my database using Ajax.
Currently only the ISBN field sends because I have it declared as a variable. However my question is, how do I send the other fields (name, title, author). How do I declare these also, I'm not sure what format they need to be in etc.
My JS
$(document).ready(function() { $('#submit').click(function(ev) { ev.preventDefault(); var isbn = $('#isbn_search').val(); //get isbn direct from input var url='https://www.googleapis.com/books/v1/volumes?q='+isbn; $.getJSON(url,function(data){ $.each(data.items, function(entryIndex, entry){ var html = '<div class="results well">'; html += '<h3>' + entry.volumeInfo.title + '</h3>'; html += '<div class="author">' + entry.volumeInfo.authors + '</div>'; html += '<div class="description">' + entry.volumeInfo.description + '</div>'; }); }); }); });My Ajax; $.ajax({ type: 'POST', url: 'addIsbnScript.php', data: { 'isbn' : isbn, 'title' : title 'subtitle' : subtitle, 'authors' : authors, 'description' : description }, success: function () { $.growl({ message: " Record added" }); } });Note, if i manually set the vars like below they all do successfully send to my database, so I know my query is working ok var title = "some text", var author = "some text", Var description = "some text"Thanks in advance for any help, newbie here (incase it wasn't obvious!). J So when I load my paginator it returns No Results Found. 1) My query is only returning 1 array entry, should be hundreds, maybe I'm not builing it correctly, 2) There is at least 1 array set but its still saying data not found. Heres the template array: Code: [Select] array('id'=>'0', 'name'=>'xmlqoyzgmykrphvyiz', 'date'=>'13-Sep-2002', 'price'=>'8370', 'number'=>'8056', 'address'=>'qdfbc', 'company'=>'taufrid', 'desc'=>'pppzhfhcdqcvbirw', 'age'=>'5512', 'title'=>'zticbcd', 'phone'=>'hvdkltabshgakjqmfrvxo', 'email'=>'eodnqepua', 'zip'=>'eodnqepua', 'country'=>'pdibxicpqipbsgnxyjumsza'), array('id'=>'1', 'name'=>'rbdmbabficcre', 'date'=>'10-Sep-2004', 'price'=>'3075', 'number'=>'3627', 'address'=>'oxcm', 'company'=>'xyzwzv', 'desc'=>'rwndyoedxh', 'age'=>'2134', 'title'=>'lxxyfgdtdffjce', 'phone'=>'zeejvbwy', 'email'=>'ldcikhxwfuulaxeedkogpxftb', 'zip'=>'ldcikhxwfuulaxeedkogpxftb', 'country'=>'pcmobxrdfclcyrx'), array('id'=>'2', 'name'=>'yr', 'date'=>'04-Mar-2007', 'price'=>'7129', 'number'=>'6614', 'address'=>'i', 'company'=>'gcpvrshftfxxlz', 'desc'=>'nyalrdjjl', 'age'=>'4728', 'title'=>'ddfl', 'phone'=>'mnhifzqltvirgiaug', 'email'=>'f', 'zip'=>'f', 'country'=>'epipbmtfsfxetenyedjxzsog'), etc Here is my arry: Code: [Select] $echoarray = array(); $resultsql = mysql_query("SELECT * FROM clients")or die(mysql_error()); while($row = mysql_fetch_array($resultsql)){ $echoarray['id'] = $row['ID']; $echoarray['name'] = $row['First_Name'] . " " . $row['Last_Name']; $echoarray['price'] = $row['Status']; $echoarray['number'] = $row['Sex']; $echoarray['address'] = $row['Phys_Street']; $echoarray['company'] = $row['Agency']; $echoarray['desc'] = $row['Notes']; $echoarray['age'] = $row['Date_Birth']; $echoarray['title'] = $row['Occupation']; $echoarray['phone'] = $row['Phone']; $echoarray['email'] = $row['Email']; $echoarray['zip'] = $row['Phys_Zip']; $echoarray['country'] = $row['Phys_City']; } Here is the template return: Code: [Select] function initArray() { return array( array('id'=>'0', 'name'=>'xmlqoyzgmykrphvyiz', 'date'=>'13-Sep-2002', 'price'=>'8370', 'number'=>'8056', 'address'=>'qdfbc', 'company'=>'taufrid', 'desc'=>'pppzhfhcdqcvbirw', 'age'=>'5512', 'title'=>'zticbcd', 'phone'=>'hvdkltabshgakjqmfrvxo', 'email'=>'eodnqepua', 'zip'=>'eodnqepua', 'country'=>'pdibxicpqipbsgnxyjumsza'), array('id'=>'1', 'name'=>'rbdmbabficcre', 'date'=>'10-Sep-2004', 'price'=>'3075', 'number'=>'3627', 'address'=>'oxcm', 'company'=>'xyzwzv', 'desc'=>'rwndyoedxh', 'age'=>'2134', 'title'=>'lxxyfgdtdffjce', 'phone'=>'zeejvbwy', 'email'=>'ldcikhxwfuulaxeedkogpxftb', 'zip'=>'ldcikhxwfuulaxeedkogpxftb', 'country'=>'pcmobxrdfclcyrx'), array('id'=>'2', 'name'=>'yr', 'date'=>'04-Mar-2007', 'price'=>'7129', 'number'=>'6614', 'address'=>'i', 'company'=>'gcpvrshftfxxlz', 'desc'=>'nyalrdjjl', 'age'=>'4728', 'title'=>'ddfl', 'phone'=>'mnhifzqltvirgiaug', 'email'=>'f', 'zip'=>'f', 'country'=>'epipbmtfsfxetenyedjxzsog'), array('id'=>'3', 'name'=>'bhqggvwolybfdtk', 'date'=>'26-Dec-2000', 'price'=>'1867', 'number'=>'4288', 'address'=>'jo', 'company'=>'goevufkvmbct', 'desc'=>'zhixinabyazbfleozrvovr', 'age'=>'3423', 'title'=>'b', 'phone'=>'odhh', 'email'=>'g', 'zip'=>'g', 'country'=>'idxvdztezvkkaz')); } And Mine: Code: [Select] function initArray() { return $echoarray; } Where am I going wrong here? Hi- I have to post to a URL, grab one field our of the JSON output/response and format nicely to the user. I've tried a few things with some help but none seem to be working. So any help or direction would be greatly appreciate it!! Attempt 1 (works but not formatted nicely) if I post using the browser, it works. the data is sent to the URL (web service) and I can see in the web service logs that the entry has been recorded. the problem is that since i have the URL in "action", i'm taken to that page and the user gets to see the JSON output Code: [Select] //here's the HTML form in offer.php <form action="http://somewebservice.com/<?php echo $PrizeID;?>" method="post" name="myform"> <input name="account" id="account" type="hidden" value="<?php echo $account;?>"/> <input name="dob" id="dob" type="hidden" value="<?php echo $dob;?>"/> <input name="site" id="site" type="hidden" value="<?php echo $site;?>"/> <input id="submit" type="submit" value="submit"/> </form> //here's the output (JSON) after clicking submit {"Prize":"XXXXXX","ConfirmationCode":"######","Error":false,"ErrorMsg":null} Attempt 2 (doens't work) i tried using php but after submit, the page refreshes and no entry is recorded in the web service log Code: [Select] //here's the HTML form in offer.php <form name="myform"> <input name="account" id="account" type="hidden" value="<?php echo $account;?>"/> <input name="dob" id="dob" type="hidden" value="<?php echo $dob;?>"/> <input name="site" id="site" type="hidden" value="<?php echo $site;?>"/> <input id="submit" type="submit" value="submit"/> //here's the php in offer.php <?php if(isset($_POST['submit'])){ $options = array( 'http'=>array( 'method'=>"POST", 'content'=>http_build_query(array( 'account' => $account, 'dob' => $dob, 'site' => $site )) )); $context = stream_context_create($options); $result = file_get_contents("http://somewebservice.com/{$PrizeID}",NULL,$context); var_dump($result); } ?> Last attempt (doesn't work) i tried using php & curl so that i can process in the back and show only the ConfirmationCode to the user in a nice format but it doesn't work. after submit, i'm taken to process.php where i see nothing and no entry is recorded in the web service log Code: [Select] //here's the HTML form in offer.php <form action="process.php" method="post" name="myform"> <input name="account" id="account" type="hidden" value="<?php echo $account;?>"/> <input name="dob" id="dob" type="hidden" value="<?php echo $dob;?>"/> <input name="site" id="site" type="hidden" value="<?php echo $site;?>"/> <input id="submit" type="submit" value="submit"/> </form> //here's the PHP in process.php <?php $postvars=file_get_contents("php://input"); $curl=curl_init("http://somewebservice.com/{$PrizeID}"); curl_setopt($curl,CURLOPT_POSTFIELDS,$postvars); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result=curl_exec($curl); $decodedresult=json_decode($result,true); ?> i haven't gotten to the point where i grab the ConfirmationCode I want because i want to get this fixed first and also because i can't get that to work but will focus on that once i fix this. Thanks. <?php ini_set('display_errors', 0); function escapeArray($array) { foreach ($array as $key => $val) { if(is_array($val)){ $array[$key]=escapeArray($val); } else{ $array[$key]=addslashes($val); } } return $array; } $request_type=$_SERVER['REQUEST_METHOD']; $api_key=$_SERVER['HTTP_X_API_KEY']; $res=array(); if($api_key!=="643256432"){ $res['msg']="Failu Invalid API KEY"; echo json_encode($res); die; } // Connects to the orcl service (i.e. database) on the "localhost" machine //$conn = oci_connect('SCOTT', 'admin123', 'localhost/orcl'); $conn = oci_connect('test', 'test', '192.168.10.43/test.test.com'); if (!$conn) { $e = oci_error(); trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR); } $request=file_get_contents("php://input"); $request=escapeArray(json_decode($request,true)); print_r($request); // die; if($request_type=="POST"){//for creation of invoice echo $CONTACT_ID=isset($request['CONTACT_ID'])?$request['CONTACT_ID']:""; $INV_SERIAL_NO=isset($request['INV_SERIAL_NO'])?$request['INV_SERIAL_NO']:""; $NAME=isset($request['NAME'])?$request['NAME']:""; $INV_DATE=isset($request['INV_DATE'])?$request['INV_DATE']:""; $DUE_DATE=isset($request['DUE_DATE'])?$request['DUE_DATE']:""; $CURRENCY=isset($request['CURRENCY'])?$request['CURRENCY']:""; $SUBTOTAL=isset($request['SUBTOTAL'])?$request['SUBTOTAL']:""; $TAX_TOTAL=isset($request['TAX_TOTAL'])?$request['TAX_TOTAL']:""; echo $SHIP_SERIAL_NO=isset($request['SHIP_SERIAL_NO'])?$request['SHIP_SERIAL_NO']:""; $MASTER_NO=isset($request['MASTER_NO'])?$request['MASTER_NO']:""; $HOUSE_NO=isset($request['HOUSE_NO'])?$request['HOUSE_NO']:""; $shipment_data=isset($request['shipment_data'])?$request['shipment_data']:""; if($CONTACT_ID==""){ $res['msg']="CONTACT_ID is required"; } else if($INV_SERIAL_NO==""){ $res['msg']="INV_SERIAL_NO is required"; } else if($NAME==""){ $res['msg']="NAME is required"; } else if($INV_DATE==""){ $res['msg']="INV_DATE is required"; } else if($DUE_DATE==""){ $res['msg']="DUE_DATE is required"; } else if($CURRENCY==""){ $res['msg']="CURRENCY is required"; } else if($SUBTOTAL==""){ $res['msg']="SUBTOTAL is required"; } else if($TAX_TOTAL==""){ $res['msg']="TAX_TOTAL is required"; } else if($MASTER_NO==""){ $res['msg']="MASTER_NO is required"; } else if($HOUSE_NO==""){ $res['msg']="HOUSE_NO is required"; } else if($SHIP_SERIAL_NO==""){ $res['msg']="SHIP_SERIAL_NO is required"; } else{ $stid = oci_parse($conn, "Select * from FL_HDR_INVOICE where CONTACT_ID='$CONTACT_ID'"); (oci_execute($stid)); oci_fetch_all($stid, $out); if(count($out['CONTACT_ID'])==0){ $stid = oci_parse($conn, "Insert into FL_HDR_INVOICE (CONTACT_ID,INV_SERIAL_NO,NAME,INV_DATE,DUE_DATE,CURRENCY,SUBTOTAL,TAX_TOTAL) Values ('$CONTACT_ID','$INV_SERIAL_NO','$NAME',TO_DATE('$INV_DATE','YYYY-MM-DD'),TO_DATE('$DUE_DATE','YYYY-MM-DD'),'$CURRENCY','$SUBTOTAL','$TAX_TOTAL')"); oci_execute($stid); $stid_2 = oci_parse($conn, "Insert into FL_SHIPMENT_DATA (CONTACT_ID,INV_SERIAL_NO,SHIP_SERIAL_NO,MASTER_NO,HOUSE_NO) Values ('$CONTACT_ID','$INV_SERIAL_NO','$SHIP_SERIAL_NO','$MASTER_NO','$HOUSE_NO')"); oci_execute($stid_2); if(oci_num_rows($stid)>0){ $res['msg']="Invoice created successfully against this contact_id:".$CONTACT_ID; } else{ $res['msg']="Something going wrong please try again later"; } } else{ $res['msg']="contact_id must be unique"; } } echo json_encode($res); die; } I need to read json data inside an array. Please help correct my code.. i am trying to do an API. I am retrieving data from a third party's API using AJAX method. I would like to do two things. 1. Display the data records on a page. 2. Create a pagination on the page to display records more efficiently. I am expecting to retrieve possibly hundreds of records. I can normally do this using PHP but since I am retrieving the records using AJAX, the pagination is gonna be a challenge. First things first is to display the records. Here is my AJAX code. It displays the log data fine. But it doesn't display any data in the "output" div. And it gives this error in the console. Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) at Object.success <div class="output"></div> <script> $.ajax ({ type: 'GET', url: "https://3rdpartywebsite.com/api/GetCustomers", dataType: 'json', processData: false, contentType: false, success: function(data) { console.log(data) $newData = JSON.parse(data); $.each($newData, function(i, v) { $('.output').append(v.LastName); $('.output').append(v.FirstName); }); } }); </script>
What am I doing wrong? Edited November 14, 2020 by imgroootHi, I have a problem with some code not working. I need it to get the data from a mysql database and then export it as a json array in the format of id , title, author, date, imageUrl, text. (Please not that these are all variables ) PHP CODE: Code: [Select] <?php $link = mysql_connect('localhost', 'root', ''); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; $arr = array(); $rs = ("SELECT `id`, `title`, `author`, `date`, `imageUrl`, `text` FROM `items`"); while($obj = mysql_query($rs)) { $arr[0] = $obj->id; $arr[1] = $obj->title; $arr[2] = $obj->author; $arr[3] = $obj->date; $arr[4] = $obj->imageUrl; $arr[5] = $obj->text; } echo '{"items":'.json_encode($arr).'}'; ?> Thanks For Your Help borden0108 Hello, I have a table with people and some details insde. So, my question is if my MySQL architecture down below is good or not. Should I devide the table into two tables and kept only p_id, p_name and p_slug inside my table (people_tbl). Thank you!
p = person
people_tbl +------+---------+---------+---------------+-------------+-------------------+-----------+------------+---------+ | p_id | p_name | p_title | p_description | p_seo_title | p_seo_description | p_country | p_category | p_slug | +------+---------+---------+---------------+-------------+-------------------+-----------+------------+---------+ | 1 | John Li | title | johns bio | 70 charsets | 170 charsets | Germany | 1 | john-li | | 2 | Bob Stu | title | bobs bio | 70 charsets | 170 charsets | Italy | 2 | bob-stu | +------+---------+---------+---------------+-------------+-------------------+-----------+------------+---------+ Edited February 16, 2020 by mactron This is more of a database architect question.
I am building a CMS for website development. I am ready to use it for the first time on one of my clients. Now, my issue is is how to set up some or one of my table(s) for some areas that my client wants to be able to change in the admin section.
In their website on the front page, I put together this nice block slider. Its 6 blocks with text, a background image and nice effects. At first it was always going to be static, which was no issue at all, but later they came to me and asked if they could be able to change words in the boxes themselves in the admin section..
Of course this can be easily done by creating a table that is associated with this home page block thing and each row in the table will correspond to one of the blocks on the home page.
But I believe there might be an easier way to store this type of data without having to create another table for every feature the client wants to edit, for example they also want to be able to edit a slider on another page.
The WordPress database then came into my mind and how they store most of their data as JSON. So I was then thinking of creating a table named 'modules' for examples with three columns (id, title, data). Then inside the data column store the editable fields as a JSON string object.
For example a row could like like :
1, "Front Page Box Slider", {"slider-home" : [ {"data" : "value", "img_1", "value1"}, {"data" : "value", "img_2", "value2"} ]}
I've been doing a bit of research on this and people have just been saying, never do this if you do want your data to be searched through, which I don't.
Can anyone tell me why or why not I should do this, or maybe a better solution to my problem?
Thank you
Edited by carlosmoreeira, 17 September 2014 - 07:37 PM. This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=318519.0 I implemented the Content-Security-Policy (CSP). I also included the report-uri so it sends a POST request to myserver.com/csp-report.php test.php <?php header("Content-Security-Policy: default-src 'self'; report-uri http://127.0.0.1/csp-report.php"); ?>I attempted to run these two inline scripts in my test.php file. <img src="http://evil.example.com/image.png"> <script>alert('XSS');</script>nothing is saved in the report-uri file! However, using Firebug, the policy is working as it should. Kindly advise if I have the report-uri synthax wrongly. Thank you Edited by terungwa, 20 October 2014 - 09:06 AM. Hi Guys, im really hoping one of you php guru's can shed some light on this as its being bugging me for months... Im trying you access a php include, in a page 1 directory deep into a site (say one down from the index.php) - with no luck. My includes are in a folder that is on the same level as the index.php file for the website. Iv tried using this way: <? include("../includes/footer.php"); ?> And this way: <?php include $_SERVER['DOCUMENT_ROOT'] . "includes/footer.php"; ?> It works locally (using MAMP), but not live on the net. Im getting this error: Warning: main() [function.main]: open_basedir restriction in effect. File(/ext/default/includes/footer.php) is not within the allowed path(s): (.:/tmp) in /ext/f/fo/fourthelement.com/html/sita/resources/members_area.php on line 53 Warning: main(/ext/default/includes/footer.php) [function.main]: failed to open stream: Operation not permitted in /ext/f/fo/fourthelement.com/html/sita/resources/members_area.php on line 53 Warning: main() [function.include]: Failed opening '/ext/default/includes/footer.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /ext/f/fo/fourthelement.com/html/sita/resources/members_area.php on line 53 Really appreciate anyone who has a few minutes to look at this. Cheers Guys Mike Hi, I have a connection set up to an API using a PHP script - the API sends back data in JSON format, and if I capture it and echo it, it displays in extremely unfriendly format on the screen. I've tried to find a way to convert this data into readable format, ideally in a HTML table, but although there are articles on converting manually inputted JSON data into a HTML table using Javascript, I can't find a way to do it from a PHP variable. This is what I have so far: if ($_POST['getcompany']) { $companyname = $_POST['_Name']; $ch = curl_init(); $data_array2 = array( 'token' => $token ); $make_call2 = json_encode($data_array2); //echo 'Token is '.$token; $token2 = substr($token, 14); $token3 = substr($token2, 0, -3); //echo 'Token 2 is '.$token3; //echo 'Company Name is '.$companyname; //curl_setopt($ch, CURLOPT_GET, 1); //curl_setopt($ch, CURLOPT_POSTFIELDS, $make_call2); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Authorization: '.$token3.'')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, 'https://connectionurl?countries=GB&name='.$companyname); //Execute the request $result = curl_exec($ch); echo 'Companies: '.$result; //This displays the data provided by the search, but is in JSON format
So I need a way to get the data held in $result, into a HTML table. Any idea how I can do this? I need to set a deep property if it is undefined or NULL such as shown below: function setProperty($value, stdClass $config, $p1, $p2, $p3, $p4) { if(!isset($config->$p1->$p2->$p3->$p4) || is_null($config->$p1->$p2->$p3->$p4)) { $config->$p1->$p2->$p3->$p4=$value; } } $config=json_decode(json_encode(['a'=>['b'=>['c'=>['x'=>null, 'y'=>123]], 'x'=>123],'x'=>['x'=>123], 'x'=>123])); setProperty(321, $config, 'a','b','c','x'); setProperty(321, $config, 'a','b','c','y'); But I wish the function to work regardless of property depth and came up with the following. Recommendations for a cleaner way? Maybe I should be working with arrays and array_merge_recursive()? function setProperty($value, stdClass $config, array $properties) { $property=array_shift($properties); if(!count($properties)){ if(!isset($config->$property) || is_null($config->$property)) { $config->$property=$value; } } else { if(empty($config->$property) || !is_object($config->$property)) { $config->$property=new \stdClass(); } setProperty($value, $config->$property, $properties); } } $config=json_decode(json_encode(['a'=>['b'=>['c'=>['x'=>null, 'y'=>123]], 'x'=>123],'x'=>['x'=>123], 'x'=>123])); setProperty(321, $config, ['a','b','c','x']); setProperty(321, $config, ['a','b','c','y']);
Hello. I have some "finish" time in ms. (for example 14000 [14s]). Also I have others guy time like 16789ms. I have made function to math difference between times. Code: [Select] function format_time($t) // t = miliseconds { $t1 = 16789; $t2 = 14000; $t = $t1 - $t2; $minutes = floor($t / 60000); $seconds = sprintf('%02d',floor(($t / 1000) % 60)); $ms = sprintf('%03d', $t % 1000); return $minutes . ":" . $seconds . "." . $ms; } echo "+ "; echo format_time($t); So it will be "+ 0:02.789" I still have a problem yet. I need to make this script mathing more than 1 time. I need around 20 other times to be mathed with 1st finish time and the difference to be displayed. And that's my problem. Can you give me examples or clues how can I give this script values in ms? Then, it should math every value and echo it somewhere. Can you help me in it, please? Let's say I'm requesting a 5 megabyte data file with cURL. I want to echo it for the user as it gets downloaded with cURL. Is there any way to do this? I'm also just using cURL as an example, it could be file_get_contents(), or something else as well. Thanks! |