Can I store a pre-made array traversal?
I want to store several API calls, and also how I get to the relevant information from their response.
For example:
$url = 'http://maps.googleapis.com/maps/api/elevation/json?locations='.$location->$latitude.','.$location->$longitude.'&sensor=true';
$response = json_decode(file_get_contents($url), true);
$result = $response['results'][0]['elevation'];
Can I save this part as a string, for storage in my DB or a variable:
$elevation = "['results'][0]['elevation']";
Then later somehow use it to parse the response, ie.
$result = $response[$elevation];
The answer is no, sorry ! you will need to store your $response as it is and call it later on using the correct format $response['results'][0]['elevation']
You may however want to use serialize() if the problem is about how to persist the array into your database:
$db->insert(serialize($reponse));
then when you retrieve the response from your db use unserialize:
$response=unserialize($db->fetchReponse());
$elevation=$response['results'][0]['elevation'];
EDIT
Based on your comment below it seems what you need is a Cache. Whereby prior to sending the request to the web service API, your application checks in a cache to see if you already have the data available locally. As above example you would most likely want to serialize the PHP array or simply cache the raw response, given that it is in JSON format (PHP serialization will create something very similar anyway).
You would create the Cache key from the query params : location, etc.
Your cached object can be stored in a DB if you choose or on the file system, or even in Memory.
Check out ZF2 Cache component :
http://framework.zend.com/manual/2.0/en/modules/zend.cache.storage.adapter.html
Related
I've been looking around at similar topics on REST APIs but I am still having some confusion in my project, mostly with the PHP side of things.
USPS provides a REST API with functions that can be called via URL like this: https://epfws.usps.gov/ws/resources/epf/login
To make any call successfully, I have been told that a JSON object must be created and passed as a "POST parameter" with the expected values.
This is the JSON object that needs to be passed in this case:
obj=
{
"login":"loginExample",
"pword":"passwordExample"
}
I have also been given a PHP class that is supposed to manage these calls. This is the login function:
public function login ()
{
// Set up the parameters for a login attempt
$jsonData = array(
'login' => $this->loginUser,
'pword' => $this->loginPass,
);
// Make a login request
$jsonResponse = $this->pullResource
('/epf/login', 'POST', $jsonData);
return $jsonResponse;
}
So I have a few questions regarding this:
The document they sent says
"To make the request calls, a JSON object will need to be created and passed as a POST form parameter obj={jsonObject} for security reasons using content-type “application/x-www-form-urlencoded”."
I know that the login function contains the correct input values that USPS' REST API is wanting, but I'm not sure how to pass them as "obj", or how to apply the "content-type".
I have a "constant" defined at the top of my PHP script that looks like this:
const EPF_BASE_URL = 'https://epfws.usps.gov/ws/resources';
And I noticed in the actual functions that this part of the link is left out and they simply reference '/epf/login' as you can see above. Since "$this" contains lots of different values I'm wondering how it supposedly finds EPF_BASE_URL as needed. Is it similar to how 'using' directives work in C#?
What is the easiest way to call this function and display the result? This is my biggest question. Would I use a separate PHP class with an HTML form? I understand the concept of what it should do but I'm completely lost setting up a development environment for it.
I've been trying all of this with MAMP but would love to know if I'm on the right track or not.
That really depends on their API. Hopefully you get a string back that can be decoded to a JSON object (http://au.php.net/manual/en/function.json-decode.php). Some API might give a simple string that says 'SUCCESS' or 'FAIL'. You've got the code, so take a look at what $this->pullResponse() gives you.
If you've been given a PHP class that is supposed to support the API (hopefully from USPS), then it should already take care of putting the data in the form content, and ensuring is it submitted with the appropriate content-type.
A PHP const is more like a C# static string. It is very likely that the library will use the constant to create the end URL (i.e. EPF_BASE_URL . $resource). If you needed to run against a sand box environment, you could change that constant without having to change all the other code.
That's a very big question, because it depends on how you are programming your application. Procedural, MVC, existing frameworks, etc.
At the very least, you would set the loginUser and loginPass on the instantiated object, and call the login method`. You could then inspect the results, assuming the result is a JSON object, or use your favourite debugging method to see the contents.
I'm having a guess as the USPS API class name.
$uspsApi = new UspsApi();
$uspsApi->loginUser = 'username';
$uspsApi->loginPass = 'password';
$result = $uspsApi->login();
echo print_r($result, true);
I'm currently coding one of my first php applications.
The application has to connect to a LDAP server and change some user attributes in the directory.
That application has some parameters to read in a mySQL Database in order to run.
Some examples of these parameters could be:
-LDAP Address
-LDAP Service Account
-LDAP Password
there are much more parameters, which rule, for example, the way users authenticate to my application,...
Currently, the database is read at each user session initialization, but, it doesn't have any sense because parameters do not vary from a session to another.
So, i'm looking for a way to load these parameters from the database, only one time (for example, at the php service initialization), and access to these parameters in the "normal" php code through variables.
What would be the best way to do this?
Thank you in advance.
You are looking for a persistent cross-request storage. There are many options for this.
The simplest is APCu (which can be used in conjunction with Zend OpCache, or for PHP < 5.5, APC).
Simply:
if (apc_exists('mykey')) {
$data = apc_fetch('mykey');
} else {
// create it from scratch
apc_store('mike', $data);
}
$data can be most any PHP type, arrays, objects, or scalars.
You can even put this code in the auto_prepend_file INI setting so it is run automatically on every request.
However: this is per server (and per SAPI, so mod_php/php-fpm/cli don't share the cache) so you will have to create it once per server.
Alternatively, for a multi-server setup you can use something like memcached or redis. These are stand-alone daemons that will let you store arbitrary key/value pairs of string data (so you may need to serialize()/unserialize() on the values).
I personally prefer memcache, which has two extensions for PHP, pecl/memcached and pecl/memcache (I prefer pecl/memcached, it has more features).
Both of them are pretty simple.
pecl/memcached:
$memcache = new Memcached();
$memcache->addServer('localhost', '11211');
$data = $memcache->get('mykey');
if (empty($data)) {
// Create data
$memcache->set('mykey', $data);
}
pecl/memcache:
$memcache = new Memcache();
$memcache->connect(); // uses localhost:11211, the default memcache host/port
$data = $memcache->get('mykey');
if (empty($data)) {
// Create data
$memcache->set('mykey', $data);
}
Both extensions support storage of arrays and objects without serialization.
You can of course store multiple keys with any of these solutions and just pull them all, instead of using one, or one with an array/object.
You can use Memcache do cache database requests. See here how to use.
Another way is using Php Sessions.
<?php
session_start(); // need to be before any html code
$_SESSION['something'] = 'Something here...';
echo $_SESSION['something']; // will show "Something here..."
And you can remove using...
unset($_SESSION['something']);
You also can use cookies, using the function setcookie. See here.
And you can get cookies using...
echo $_COOKIE['something'];
Production mode
In a production mode, this will work as set_transient of Wordpress. You will do the first db request to get the value and will cache this value using cookies, sessions or memcache.
If you want to show this values inside of your page, you can use a standard caching library.
My understanding of the question is that you have some SQL data that is more or less constant and you don't want to have to read that in from the SQL connection on every request.
If that is the case you can use memcache to store the data:
http://php.net/manual/en/book.memcache.php
The data will still be persistent and you will only need to go to the database if the cached data isn't there or needs to be refreshed.
If the data is specific to a particular user you can just use a session.
http://php.net/manual/en/book.session.php
http://php.net/manual/en/session.examples.basic.php
If this is only to be used when starting up your server (so once and done) and you don't want to bother to with memcached/xcache (as they would be over kill) you can still use environment variables. See get_env
I'm trying to use the data.gov.uk to grab the court data and do cool stuff with it. Problem I am having is if I try to decode the version from the server in php: https://courttribunalfinder.service.gov.uk/api.html it just won't load. It only works if I download the courts.json file and decode from that. However then I'm unable to query the data with something like courts.json?q=bristol say.
So my question is, should I be able to decode directly from the gov website or do I need to do it locally, and if that's the case how would I allow me to feed query strings to my local json file?
e.g. I want to be able to do something like:
$jsonurl = directory() . '/courts.json?q=old+bailey';
$json = wp_remote_get($jsonurl,0,null,null);
$court = json_decode($json['body'], true);
well,
There are two options for you
1) Use cURL Library as mentioned by Joanvo
2) use YQL(Yahoo Query Language) that is also another powerful thing around.
I'm using HTTPful to send some requests in PHP and get data in JSON, but the library is converting the result into objects, where I want the result to be an array. In other words, its doing a json_decode($data) rather than json_decode($data, true).
There is, somewhere, an option to use the latter, but I can't figure out where. The option was added in v0.2.2:
- FEATURE Add support for parsing JSON responses as associative arrays instead of objects
But I've been reading documentation and even the source, and I don't see the option anywhere... The only way I can think of is making my own MimeHandlerAdapter which does a json_decode($data, true) but it seems like a pretty backwards way of doing it if there is an option somewhere...
It may be a little late to answer this, but I did a little research while using Httpful and found the answer. Httpful uses a default set of handlers for each mime type. If one is registered before you send the request, it will use the one you registered. Conveniently, there is an Httpful\Handlers\JsonHandler class. The constructor takes an array of arguments. The only one it uses is $decode_as_array. Therefore, you can make it return an array like this:
// Create the handler
$json_handler = new Httpful\Handlers\JsonHandler(array('decode_as_array' => true));
// Register it with Httpful
Httpful\Httpful::register('application/json', $json_handler);
// Send the request
$response = Request::get('some-url')->send();
UPDATE
I realized that it sometimes parses the response into a funky array if you don't tell the request to expect JSON. The docs say it's supposed to work automagically, but I was having some issues with it. Therefore, if you get weird output, try explicitly telling the request to expect JSON like so:
$response = Request::get('some/awesome/url')
->expects('application/json')
->send();
I never used this library. But in a research I found that you can find this option at src/Httpful/Handlers/JsonHandler.php on line 11.
There you will see:
private $decode_as_array = false;
And this flag is used at the same file on line 27:
$parsed = json_decode($body, $this->decode_as_array);
You have to set decode_as_array to true value, to do this:
\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(array('decode_as_array' => true)));
before Request::get calling
I have to read a file and do some computation, than save the result of this computation inside a variable.
I just need to do this once. In Java + Servlet I can do this using a servlet container and, for instance, the singleton pattern.
I know that in PHP I can't act like this. Which is the better way to do this? Save the computation (or transfer the data) on DB?
No, it won't work like with Java Servlets. You'll have to find a workaround.
First, I assume that using $_SESSION, $_COOKIE or $_REQUEST in general isn't practicable to you as you want to save the state per server (or per application) and not per 'User Session'.
Using a database sounds practicable in your case. In a regular application design it will be the most common solution.
Also you can do something like this, using the serialization capabilities of PHP:
<?php
$resultfile = 'result.dat';
if(!file_exists($resultfile)) {
$result = compute_result('foo bar');
file_put_contents($resultfile, serialize($result));
} else {
$result = unserialize(file_get_contents($resultfile));
}
Using PHP's serialize() attempt is especially practicable when
You are in a PHP only environment
$result is a complex datatype but you don't want to create a database structure and map $result too it
If you are not in a PHP only environment you might prefer other serialization formats as JSON or XML.
Also the serialization result can be stored as a string in a database instead of a file. Saving it to a database instead of a file would make the application more scalable as the result would be available to all servers that access the same database (cluster).
In short: I would suggest using a database maybe combined with serialization.