Someone Help Me To Print This Array Using Css Or In Tables - php

Can someone please help me to print this data using tables or css or bootstrap..?
PHP Code Used:
$url = "http://some-website.com/api/message";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
$json = json_decode($content, true);
$count=count($json);
print_r ($json);
Result:
Array
(
[success] => 1
[result] => Array
(
[0] => Array
(
[id] => 12491055
[device_id] => 18398
[message] => hi there!
[status] => received
[send_at] => 0
[queued_at] => 0
[sent_at] => 0
[delivered_at] => 0
[expires_at] => 0
[canceled_at] => 0
[failed_at] => 0
[received_at] => 1456228673
[error] => N/A
[created_at] => 1456271873
[contact] => Array
(
[id] => 3077686
[name] => charan
[number] => 123456789
)
)
)
)
I'm new in this php field so don't try to make your answers bit difficult one for me to understand or execute.
i want it to be printed like:
Name: some one
Message: Hi
Etc.........
just like online desposal mobile numbers & message's services sites
Thanks In Advance!

Just look at the array you already have, and drill down.
echo "Name: " . $json['result'][0]['contact']['name'];
Or:
echo "Message: " . $json['result'][0]['message'];

use foreach() to print your array.example:
$tab=array('name'=>'Jack','last name'=>'sparrow');
foreach($tab as $key=>$elem)
{
echo "$key : $elem <br>";
}
//the result
//name: jack
//last name : sparrow

Related

How do I get an element from JSON in PHP?

I have this output from a JSON. How can I get one element (for example "etternavn" ) into a PHP variable. This is the output I get for the whole thing:
stdClass Object (
[hitLinesBeforeFilter] => 1
[userID] => 632
[1] => stdClass Object (
[listing] => stdClass Object (
[table] => listing
[id] => 1402864
[duplicates] => Array (
[0] => stdClass Object (
[table] => listing
[id] => 1402864:0
[idlinje] => D1FIJFT000
[tlfnr] => 41428798
[etternavn] => Bumpy Bones Interactive Cornelius Gutsu
[veinavn] => Hans Nielsen Hauges vei
[husnr] => 48F
[postnr] => 1523
[virkkode] => N
[apparattype] => M
[kilde] => D
[foretaksnr] => 998209609
[bransjekode] => 15636
[prioritet] => 0
[kommunenr] => 104
[poststed] => Moss
[kommune] => Moss
[fylke] => Østfold
[landsdel] => Ø
[bransjebokmaal] => Internettdesign og programmering
[bransjenynorsk] => Internett design og programmering
)
)
)
)
[dummy] =>
)
The PHP code is the following:
$json = utf8_encode(file_get_contents($url, 'UTF-8'));
$data = json_decode($json);
print_r($data->result);
I have tried echo $data->etternavn;
I know this might be a simple question, sorry. I'm not good with coding.
You can do this:
<?php
$json = utf8_encode(file_get_contents($url, 'UTF-8'));
$data = json_decode($json, true);
print_r($data['result'][1]['listing']['duplicates'][0]['etternavn']);
?>
You have to traverse through this complex structure. To get etternavn you need to do this:
$data = json_decode($json);
echo $data->result->{1}->listing->duplicates->{0}->etternavn;
Or as suggested in comments, pass next parameter of json_decode to true. Which will convert it into array.
$data = json_decode($json, true);
echo $data['result'][1]['listing']['duplicates'][0]['etternavn'];

how to access 2nd array in an associative array

I have an array returned from a json, I can access the values from one part of the array, but I can't access the values from another part of the array
echo '<strong>Barcode Number:</strong> ' . $response->products[0]->barcode_number . '<br><br>';
echo '<strong>Product Name:</strong> ' . $response->products[0]->product_name . '<br><br>';
echo '<strong>Description:</strong> ' . $response->products[0]->description . '<br><br>';
echo '<strong>Description:</strong> ' . $response->stores[0]->store_name . '<br><br>';
I get the first three fine but the last one for stores returns the error
Barcode Number: 077341125112
Product Name: Custom Accessories 89960W E-Tek Butane Torch
Description: Butane Torch, 89960W is ideal for your home garage or
your car. Can be used for quick repairs.
Notice: Undefined property: stdClass::$stores in
C:\xampp\htdocs\customs\production\test-barcodelookup.php on line 20
Notice: Trying to get property 'store_name' of non-object in
C:\xampp\htdocs\customs\production\test-barcodelookup.php on line 20
$ch = curl_init(); // Use only one cURL connection for multiple queries
$data = get_data($url, $ch);
$response = array();
$response = json_decode($data);
echo '<strong>Barcode Number:</strong> ' . $response->products[0]->barcode_number . '<br><br>';
echo '<strong>Product Name:</strong> ' . $response->products[0]->product_name . '<br><br>';
echo '<strong>Description:</strong> ' . $response->products[0]->description . '<br><br>';
echo '<strong>Description:</strong> ' . $response->stores[0]->store_name . '<br><br>';
echo '<strong>Entire Response:</strong><pre>';
print_r($response);
echo '</pre>';
function get_data($url, $ch) {
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Below is the array returned
Entire Response:
stdClass Object
(
[products] => Array
(
[0] => stdClass Object
(
[barcode_number] => 077341125112
[barcode_type] => UPC
[barcode_formats] => UPC 077341125112, EAN 0077341125112
[mpn] => 0007734112511
[model] => 89960w
[asin] =>
[product_name] => Custom Accessories 89960W E-Tek Butane Torch
[title] =>
[category] => Hardware > Tools > Hardware Torches
[manufacturer] =>
[brand] => Etek
[label] =>
[author] =>
[publisher] =>
[artist] =>
[actor] =>
[director] =>
[studio] =>
[genre] =>
[audience_rating] =>
[ingredients] =>
[nutrition_facts] =>
[color] =>
[format] =>
[package_quantity] =>
[size] =>
[length] =>
[width] =>
[height] =>
[weight] =>
[release_date] =>
[description] => Butane Torch, 89960W is ideal for your home garage or your car. Can be used for quick repairs.
[features] => Array
(
)
[images] => Array
(
[0] => https://images.barcodelookup.com/3001/30014169-1.jpg
)
[stores] => Array
(
[0] => stdClass Object
(
[store_name] => Wal-Mart.com USA, LLC
[store_price] => 14.97
[product_url] => http://www.walmart.com/ip/Custom-Accessories-89960W-E-Tek-Butane-Torch/29029306
[currency_code] => USD
[currency_symbol] => $
)
[1] => stdClass Object
(
[store_name] => Jet.com
[store_price] => 14.20
[product_url] => http://jet.com/product/detail/a43035df304c4551b45f62262402f9f2
[currency_code] => USD
[currency_symbol] => $
)
)
[reviews] => Array
(
[0] => stdClass Object
(
[name] => Ken Weber
[rating] => 5
[title] => Torch Performance
[review] => I didnt know how good this torch was until I used it and its very nice for the money. The electronic ignition fires the butane evertime. Nice feel to it. Has a trigger lock down for extended usage time. GOOD PRODUCT.
[datetime] => 2015-12-29 11:27:34
)
)
)
)
)
I am trying to access the images array and echo it out and the information from the stores array and echo it. I can get the information from the products array. but I can't figure out how to get the others
This is what I am trying to achieve
Barcode Number: 077341125112
Product Name: Custom Accessories 89960W E-Tek Butane Torch
Description: Butane Torch, 89960W is ideal for your home garage or
your car. Can be used for quick repairs.
Display Image of product.
Stores:
store_name: Wal-Mart.com USA, LLC store_price: 14.97 product_url:
http://www.walmart.com/ip/Custom-Accessories-89960W-E-Tek-Butane-Torch/29029306
store_name: Jet.com store_price: 14.20 product_url:
http://jet.com/product/detail/a43035df304c4551b45f62262402f9f2
When you format the data, it shows that the stores data is under each product, so you would need to display it as...
$response->products[0]->stores[0]->store_name
You would also probably need to use a foreach() to display all the details, both with products and the stores for each product.
foreach ( $response->products[0]->stores as $store ) {
// Echo out the details
echo $store->store_name;
}
Side-step: I think the easiest way to go about this process is using
json_decode($json, true);
This makes everything an associative array.
Here is the manual for the json_decode internal function.
Step-back:
$response->products[0]->stores[0]->store_name

Simplify an array and save as CSV [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have the really complex array:
stdClass Object
(
[matters] => Array
(
[0] => stdClass Object
(
[id] => 1050370768
[client] => stdClass Object
(
[id] => 939940280
[url] => /api/v2/contacts/939940280
[name] => Balter and Son
)
[display_number] => 00001-Balter and Son
[description] => Sueing for pain of having to program
[status] => Open
[open_date] => 2017-07-26
[close_date] =>
[pending_date] =>
[location] =>
[client_reference] => 34241
[responsible_attorney] => stdClass Object
(
[id] => 345011996
[url] => /api/v2/users/345011996
[name] => jon balter
[email] => jbalter#seamlesssolutions.com
)
[originating_attorney] =>
[practice_area] =>
[billable] => 1
[maildrop_address] => ecd6d7b60+matter1050370768#maildrop.clio.com
[created_at] => 2017-07-26T20:46:14+00:00
[updated_at] => 2017-07-26T20:46:14+00:00
[custom_field_values] => Array
(
)
[billing_method] => hourly
[group_id] => 1654280
[permission] => stdClass Object
(
[id] => 1654280
[url] => /api/v2/groups/1654280
[name] => Firm
)
[activity_rates] => Array
(
)
)
[1] => stdClass Object
(
[id] => 1050770508
[client] => stdClass Object
(
[id] => 940983330
[url] => /api/v2/contacts/940983330
[name] => Seamless Solutions
)
[display_number] => 00002-Seamless Solutions
[description] => This is a matter of life and death
[status] => Open
[open_date] => 2017-08-09
[close_date] =>
[pending_date] =>
[location] =>
[client_reference] =>
[responsible_attorney] =>
[originating_attorney] =>
[practice_area] =>
[billable] => 1
[maildrop_address] => ecd6d7b60+matter1050770508#maildrop.clio.com
[created_at] => 2017-08-09T21:37:28+00:00
[updated_at] => 2017-08-09T21:37:28+00:00
[custom_field_values] => Array
(
)
[billing_method] => hourly
[group_id] => 1654280
[permission] => stdClass Object
(
[id] => 1654280
[url] => /api/v2/groups/1654280
[name] => Firm
)
[activity_rates] => Array
(
)
)
)
[records] => 2
[limit] => 200
[next_offset] => 1050770508
[order_dir] => asc
[total_records] => 2
[published_at] => 2017-08-09T21:37:38+00:00
)
I just want to get a return of
Array (
[display_number] => 00001-Balter and Son
[display_number] => 00002-Seamless Solutions
)
Then take this and save this as a CSV
00001,Balter and Son,
00002,Seamless Solutions
Any help would be awesome.
I know there has to be an easy way to do this.
Someone asked for the PHP. Little hard to put here but I will try. It is part of an API for CLIO legal software.
//Get Matters
$matterarry = matter_numbers ($token);
//get array to just matter numbers
$matternumbers = array(); // initialize the array to be used for the export
foreach($matterarry->matters as $key => $matter) { // loop through all the top level element
// isolate the display number '00001' from '00001-Balter and Son'
$displayNumber = explode('-', $matter->display_number);
$displayNumber = $displayNumber[0];
// push the element the export array using the display_number as the key
$matternumbers[$key] = array(
$displayNumber, // '00001'
$matter->client->name // 'Balter and Son'
);
}
Print_r ($matternumbers);
//export to CSV
$f = fopen('/tmp/matternumbers.csv', 'a'); // open the destination file handler
fputcsv($f, array('display_number', 'name')); // start by adding the column headers
// this can also be done by using named keys in your array,
// or having the first element be the value of the headers
// I'm appending manually here for the sake of simplicity
foreach($matternumbers as $key => $element) {
fputcsv($f, $element); // append each element to the file
}
fclose($f); // don't forget to close the file ;)
function matter_numbers ( $token ) {
//$header = array('Authorization: bearer '.$token);
//print_r ($header);
$header = 'Authorization: bearer '.$token;
echo $header."\r\n";
$ch = curl_init();
//curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, 'https://app.goclio.com/api/v2/matters');
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($ch);
if( !$resp ) {
die('Error: "' . curl_error( $ch ) . '" - Code: ' . curl_errno( $ch ) );
}
else if ( 200 != curl_getinfo( $ch, CURLINFO_HTTP_CODE ) ) {
echo "Bad Response Code!";
echo "\n";
echo "Response HTTP Status Code : " . curl_getinfo( $ch, CURLINFO_HTTP_CODE );
echo "\n";
echo "Response HTTP Body : " . $resp;
}
//print "curl response is:" . $resp;
$resp = json_decode($resp);
//print_r ($resp);
curl_close($ch);
return $resp;
}
I'll try addressing the two parts of your question (1) simplifying the array to isolate specific elements and (2) exporting that to a .csv file
Simplifying the array
For this you'll need to iterate over all the matters element of your original object and push whatever value(s) you wish to export in a new array with the appropriate format
$exportArray = array(); // initialize the array to be used for the export
foreach($initialObject->matters as $key => $matter) { // loop through all the top level element
// isolate the display number '00001' from '00001-Balter and Son'
$displayNumber = explode('-', $matter->display_number);
$displayNumber = $displayNumber[0];
// push the element the export array using the display_number as the key
$exportArray[$key] = array(
$displayNumber, // '00001'
$matter->client->name // 'Balter and Son'
);
}
You then end up with an array that should look a little something like that:
Array [
0 => Array [
0 => '00001'
1 => 'Balter and Son'
]
1 => Array [
0 => '00002'
1 => 'Seamless solutions'
]
]
Alternatively, instead of looping over the array you could use array_map() and obtain a similar result. If you're not familiar with array_map() you can find the official doc here
$exportArray = array_map(function($matter) {
// isolate the display number '00001' from '00001-Balter and Son'
$displayNumber = explode('-', $matter->display_number);
$displayNumber = $displayNumber[0];
return array(
$displayNumber,
$matter->client->name
);
}, $initialObject->matters)
Exporting to CSV
This part is actually quite easy as PHP has a function specifically for this (Official Doc)
$f = fopen('/tmp/myFile.csv', 'a') // open the destination file handler
fputcsv($f, array('display_number', 'name')) // start by adding the column headers
// this can also be done by using named keys in your array,
// or having the first element be the value of the headers
// I'm appending manually here for the sake of simplicity
foreach($exportArray as $key => $element) {
fputcsv($f, $element); // append each element to the file
}
fclose($f) // don't forget to close the file ;)
Mixing the two together
Looping over the elements you want to export twice is tedious and will affect readability and maintainability. This is why you should probably mix those examples together in a single loop.
$file = fopen('/tmp/myFile.csv', 'a'); // open the destination file handler
fputcsv($file, array('display_number', 'name')); // add the column headers
foreach($initialObject->matters as $key => $matter) { // loop through all the top level element
// isolate the display number '00001' from '00001-Balter and Son'
$displayNumber = explode('-', $matter->display_number);
$displayNumber = $displayNumber[0];
// Add the information you need directly in the file
fputcsv($file, array($displayNumber, $matter->client->name));
}
fclose($file);
For the sake of simplicity, I have assumed that your destination file is empty. If you don't know how to make sure a file is empty before starting working with, I suggest you look at this question that sums it up very well.

Searching in json array for parameter and show correct information

Is it possible to search inside json array which I pull with curl and if match to show only that data?
The array looks like
Array
(
[status] => success
[data] => Array
(
[out] => Array
(
[0] => Array
(
[address] => test address
[amount] => 11
[type] => 1
)
[1] => Array
(
[address] => test address 1
[is_nonstandard] =>
[amount] => 12
[type] => 1
)
)
)
[code] => 200
[message] =>
)
And this is how I pull the array
function get_curl_content_tx($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
$url=get_curl_content_tx("http://example.com");
$total =json_decode($url,true);
So since there can be more that 1 arrays in [out] => Array as current situation they are two I want to search and match by [address] and when match to give data.
Here is a way to do it :
foreach($arr['data']['out'] as $d){
if(strpos($d['address'], 'testaddress') !== false){
//do something
var_dump($d);
}
}
You need to replace var_dump by whatever you want to do.
I used strpos for the sake of this example, but you might want to use a custom method that would suits your needs better
Hope this helps.
<?php
$outArray = $total['data']['out'];
foreach($outArray as $item) {
// echo $item['address'];
}
?>
Try this:
if(isset($total['data']['out'])){
foreach($total['data']['out'] as $out){
if(isset($out['address'])){
if($out['address'] == "your adress"){
//Your Stuff;
}
}
}
}

Is there any memory limit for json_encode() method?

I am trying to echo a json-encoded array which consist of an array but i dont know it is not letting me print that thing. Here's my code:
<?php
include_once('confi.php');
header('Content-type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$lastRecord = isset($_POST['lastRecordID']) ?
mysql_real_escape_string($_POST['lastRecordID']) : "";
$queryForTotalRec = mysql_query("SELECT customer_id FROM `WebServiceTesting`.`sapphire` ORDER BY customer_id DESC LIMIT 1");
$total_rec = mysql_fetch_row($queryForTotalRec);
if($total_rec){
$queryForAllRecords = "SELECT * FROM `WebServiceTesting`.`sapphire` WHERE customer_ID BETWEEN %d AND %d";
$get_all_recs = mysql_query(sprintf($queryForAllRecords, $lastRecord, $total_rec[0]));
$json = array();
while($row = mysql_fetch_assoc($get_all_recs)){
$json[] = array("Status" => 1, "NewRecord" => $row);
}
print_r($json);
echo json_encode($json);
}else{
$json = array("status" => 0, "Error_Message" => mysql_error());
echo json_encode($json);
}
}else{
$json = array("status" => 0, "Error_Message" => "Request Method not correct");
echo json_encode($json);
}
#mysql_close($conn);
Errors:
Malformed JSON: Unexpected 'A' sometimes 'I'
When i am deleting the print_r line iam getting:
No response received
When i am printing the count of $json array iam getting a count of 153 but NO OTHER output.
Things i've tried:
i read in some solutions to similar problems that u need to use array_values()
for e.g:
echo json_encode(array_values($json));
same response: 'No response received'
I've also tried putting echo $json inside loop which I know that is conceptually wrong but still and got expected error 'Syntax error'
Also, i tried echoing through foreach no luck Syntax error but i can see output in raw but cannot validate the json.
Just for the info on print_r this is the response:
Array (
[0] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1241
[firstName] => Katy
[lastName] => Lest
[email] => klest#yahoo.com [phone] => 787012425
)
)
[1] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1242
[firstName] => Hanah
[lastName] => Morrisn
[email] => road#gmail.com
[phone] => 144221275 )
)
[2] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1243
[firstName] => James
[lastName] => McGrath
[email] => rosamcgrath#hotmail.com
[phone] => 79684312 )
)
)
Just found a sort of answer to this i am still looking for a reason if anyone can help in that please. The number of Records i was pulling were 150+ so i just tried with 50 records at a time and it worked perfectly. Anyone know how can i actually allocate more memory to my array so that it can hold all the required data at once only ?
I have also tried by giving accurate index as well i thought that array goes out of memory but this even not working:
$json = new SplFixedArray($difference);
Your assistance would be very much appreciated.
Stab into the dark: some of your database rows contain non-ASCII characters (e.g. ü, é and such). Your database connection is set to latin1, so the data is not UTF-8 encoded. json_encode requires UTF-8 encoded data. If you fetch enough rows, there will be rows with such non-UTF-8 data in there, and json_encode fails. With few enough rows you happen to not hit those problematic rows.
Test this by outputting echo json_last_error_msg(); after json_encode.
Set your database connection to UTF-8. See here how to do so: UTF-8 all the way through
The reason why your browser complains about invalid JSON when you include a print_r is simple: because then PHP outputs a lot of garbage which isn't JSON, which the browser can't decode as JSON.
Simply Use json_decode() you will get the result you need..
$array = json_decode($json, true);
echo "<pre>"; print_r($array);
Array
(
[0] => Array
(
[Status] => 1
[NewRecord] => Array
(
[fname] => xyz
[lname] => abc
[gender] => male
)
)
[1] => Array
(
[Status] => 1
[NewRecord] => Array
(
[fname] => 123
[lname] => 456
[gender] => male
)
)
[2] => Array
(
[Status] => 1
[NewRecord] => Array
(
[fname] => demo
[lname] => vvv
[gender] => female
)
)
)

Categories