for web services , how to retrieve the data json format using Laravel, can anybody help
https://test.com/admin/users/apiLogin?Login={"email":test#test.com,"pwd":testing}
in Controller
public function apiLogin(Request $request)
{
//$data = $request->json()->all();
$data=json_decode($request['Login']);
echo $data['email'];
echo "<pre>";
print_r($data);
echo "</pre>";
echo "testsetet";
exit;
}
To get the URL parameter use this:
$login = $request->input('login'); // or $request['Login']
The goal is to turn login (which is a string) into appropriate JSON format so that you can use json_decode.
I'll break it down in steps:
Remove all \n characters:
$login = str_replace('\n', '', $login);
Remove last comma
$login = rtrim($login, ',');
Add brackets
$login = "[" . trim($login) . "]";
Turn it into a PHP array:
$json = json_decode($login, true);
The issue here is that your url parameter 'Login' isn't properly formatted json. I would revisit your front-end code persisting this data and ensure it is formatting properly. True json should look like:
{"email":"test#test.com","pwd":"testing"}
As a BIG aside, never persist passwords in the URL. It is dangerously foolish. Use a POST request to do this. On the plus side, the back-end code will be virtually the same with your json_decode() logic.
Related
I paid someone to make a plugin for my website 5 years ago and now I'm trying to get it to work again. I have no knowledge of how JSON works so this is my first experimenting with it. Basically my plugin would use the Iframely API to get a summary of an article and save the data to a custom field from a URL in the editor.
The code I have in question in my function.php is this:
function post_extra_save( $post_id, $post){
global $pagenow;
if ($pagenow == 'post.php') {
if ( has_post_format('link', $post_id)) {
$url = get_post_field('post_content', $post_id);
$request_url = 'https://iframe.ly/api/iframely?url='. urlencode($url) .'&api_key='.get_field_object('api_key', 'option')['value'];
$response = wp_remote_get( esc_url_raw( $request_url ) );
$api_response = json_decode( wp_remote_retrieve_body( $response ), true );
update_field('field_61942d74195e7', $api_response);
}
}
}
add_action( 'save_post', 'post_extra_save', 10, 2 );
What it does is send a URL plus the API key to Iframely API, returns the JSON and save the raw output to a custom field.
When I save the post, I get this error message:
Warning: htmlspecialchars() expects parameter 1 to be string, array given in /wp-includes/formatting.php on line 4529
Any idea what this means?
Found my problem. What I got it to work was it gets the URL from the post content, encode it from the raw JSON and decode it.
$request = wp_remote_get( 'https://iframe.ly/api/iframely?url='. urlencode($url) .'&api_key='.get_field_object('api_key', 'option')['value'] );
$data_raw = json_encode( wp_remote_retrieve_body( $request ));
$data = json_decode($data_raw);
How can I get access to JSON in a mojo response?
$txn = $ua->post( $url, $headers, json => {json} )
What's the way to get the JSON response from the txn?
I have several examples in my book Mojolicious Web Clients, but here's the deal.
When you make a request, you get back a transaction object:
my $ua = Mojo::UserAgent->new;
my $tx = $ua->post( ... );
The transaction object has both the request and response (a major feature that distinguishes Mojo from LWP and even other user agent libraries in other languages). To get the response, you can use the res or result methods. The result dies for you if it couldn't make the request because a connection error occurred (ENONETWORK):
my $res = $tx->result;
Once you have the response, there are various things you can do (and these are in the SYNOPIS section of the Mojo::UserAgent. If you want to save the result to a file, that's easy:
$res->save_to( 'some.json' );
You can turn the content into a DOM and extract parts of HTML or XML:
my #links = $res->dom->find( 'a' )->map( attr => 'href' )->each;
For a JSON response, you can extract the contents into a Perl data structure:
my $data_structure = $res->json;
However, if you wanted the raw JSON (the raw, undecoded content body), that's the message body of the request. Think of that like the literal, unfiltered text:
use Mojo::JSON qw(decode_json);
my $raw = $res->body;
my $data_strcuture = decode_json( $raw );
Since this is the response object, Mojo::Message and Mojo::Message::Response show you what you can do.
Here's a complete test program:
#!perl
use v5.12;
use warnings;
use utf8;
use Mojo::JSON qw(decode_json);
use Mojo::UserAgent;
use Mojo::Util qw(dumper);
my $ua = Mojo::UserAgent->new;
my $tx = $ua->get(
'http://httpbin.org/get',
form => {
name => 'My résumé'
},
);
die "Unsuccessful request"
unless eval { $tx->result->is_success };
my $data_structure = $tx->res->json;
say dumper( $data_structure );
my $raw = $tx->res->body;
say $raw;
my $decoded = decode_json( $raw );
say dumper( $decoded );
I was able to get access to this data like this,
my $api_order = $tx_cart->result->json->{data};
It's in result not in body.
I'm using a json-parser in Xcode to fetch a table from phpmyadmin. The parser gets (or should get) the json-formated document via a php-file uploaded on my ftp-server. The file is successfully parsed but it doesn't recognize any objects. I think this is because there are multiple arrays in the json-document.
When there's only one entry the document looks like this:
[{"id":"1","Name":"Eric","Message":"first from web"}]
but when i add an entry it looks like this:
[{"id":"1","Name":"Eric","Message":"first from web"}]
[{"id":"1","Name":"Eric","Message":"first from web"},{"id":"6","Name":"Claes","Message":"Hurrburr"}]
As you can see the old array (containing only the single entry) is still there in the second array with both entries.
I suspect the problem is that the old arrays are still there when i update the database because when i tried parsing the json document with only one entry (only one array) it worked.
So my question is first if there´s something i missed in my code, or if you know why the old arrays are still there when I update the database or how to remove all previous arrays when the document is updating.
Here is my .php-file:
<?php
$username = "perhaps not sharing this information";
$password = "or this";
$database = "nah";
mysql_connect("the server url",$username, $password);
#mysql_select_db($database) or die("Error here");
$query = "SELECT * FROM debug_db";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_numrows($result);
mysql_close();
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
echo json_encode($rows);
}
?>
And check out the json-document at: http://app.levinnovation.se/getjson.php
Thank you!
The data pulled from the database inserts into an RTF template without a problem as long as I only have 1 row. If I put my header("Content-type: text/rtf") inside the loop, however, I receive a headers already sent error. When removing the headers from the code, the raw data prints properly in the browser window.
How do I combine data from multiple records in the database to create multiple documents (or 1 document with page breaks)?
Code here:
$document='../docs/letter.rtf';
$qry="Select * from table";
$result=mysql_query($qry);
$num_row=mysql_num_rows($result);
while($row=mysql_fetch_assoc($result)){
$account_id=$row['pk_account];
$name=$row['first_name'];
$file_doc='01-'.$pk_account.'.rtf';
....
$body=file_get_contents($document);
$body=str_replace("NAME", $name, $body);
....
for($i=0; $i<$num_rows; $i++){
}
header("Content-type: text/rtf");
header("Content-Disposition:attachment; filename={$file_doc}");
echo $body;
}
You need to concatenate your $body. So instead of this:
$body=file_get_contents($document);
$body=str_replace("NAME", $name, $body);
try this:
$body.=str_replace("NAME", $name, file_get_contents($document));
Then place this outside your while loop:
header("Content-type: text/rtf");
header("Content-Disposition:attachment; filename={$file_doc}");
echo $body;
From http://json.org/:
an empty Json object is:
{}
I've tried to get it with json_encode (which is officially part of PHP):
json_encode((object)(array()))
that's what I need. But somehow I have to use Zend_json to get it:
Zend_Json::encode((object)(array()))
but the result is:
{"__className": "stdClass"}
Any ideas?
My PHP version 5.1.6; ZF version 1.7.2
For me this works perfectly:
echo '<pre>'; print_r(Zend_Json::encode((object)array())); echo '</pre>'; exit;
// Output: {}
Tested with ZF-Version 1.11.3
Also possible:
Zend_Json::encode(new stdClass());
Try
Zend_Json::encode(array());
Just in case anybody is still wondering, the internal encoder of the ZF adds the __className property to each object.
The internal encoder is used if the PECL extension json is not installed and thus the function json_encode not available (see http://php.net/manual/en/function.json-encode.php ).
Just use
preg_replace('/"__className":"[^"]+",/', '', $jsonString);
to get rid of all className elements
I find the solution as below:
$m = Zend_Json::encode($obj);
$res = str_replace('"__className":"stdClass"', '', $m);
$res = str_replace("'__className':'stdClass'", '', $res);
$res = str_replace("'__className': 'stdClass'", '', $res);
$res = str_replace('"__className": "stdClass"', '', $res);
return $res;
To get around this in Zf2 I have added a disableClassNameDecoding option to Zend\Json\Encoder.
If you want to disable the __className output, you can use it like this:
return Zend\Json\Json::encode($object, false, array('disableClassNameDecoding' => true));
The patched file can be found on github. At some point I will add unit tests and create a pull request.