Creating an API to pass an Array result in PHP - php

I am not an expert with PHP. I am creating an API in order to get some information from one of my website.
Here is the result of api.php:
array (size=4)
'price' => string '29.90' (length=5)
'activation_charge' => string '50.00' (length=5)
'decoder_price' => string '0.00' (length=4)
'is_offer' => int 0
I would like to create an API which would send these information. Here is the sample API call :
www.example.com/api.php?product=11&user=kiran
How should I encode the array results so that I can read it through an API call. I hope, the question is clear.
Thanks

How should I encode the array results so that I can read it through an API call. I hope, the question is clear.
JSON is a popular choice
json_encode http://php.net/json_encode
json_decode http://uk3.php.net/json_decode
XML is also another popular choice
http://blog.teamtreehouse.com/how-to-parse-xml-with-php5
CSV is popular depending on the data/application (and variants of; pipe-delimiter, etc)
explode http://php.net/explode

If you want to return it to Javascript for example. The easiest way is to use JSON.
echo json_encode( $array ) ;
Which will output something like:
{ "price" : 29.9, "activation_charge" : 50.0, "decoder_price" : 0.0, "is_offer" : 0 }
Of course you can create your own format and decode it on the other side.

Related

PHP script pulling information in wrong format? Trying to get it in JSON

I have a script in Python pulling information from one service and a script in PHP pulling from another. I'd like to parse and compare the data from both, so obviously I need the information to be in the same format.
The Python script returns a text file in JSON format. Here's a small snippet. Disregard the information inside. I just want to show the formatting.
{
"category": 0,
},
"cluster_seed": "24",
"clusters": {
"clusters": [
{
"center": {
"000002": [
"massachusetts",
"new hampshire",
"new jersey"
],
"000003": [
"Windows",
"OSX"
]
}
etc...
However, the PHP script returns information like this:
Array
(
[0] => Array
(
[name] => John Smith
[engagementScore] => 0
[firstActivity] => 1386555168108
[lastActivity] => 1386555168108
[attributes] => Array
(
[_deviceType] => Tablet
[_os] => Android
[_browser] => Chrome
)
[segmentMemberships] => Array
(
[0] => Array
(
[segmentationName] => example
[segementationId] => example
)
)
I'm not really sure what's going on here. I guess it's printing as a PHP object/array rather than a raw JSON file? I would like it to be formatted exactly as the first snippet is. This is the code in my PHP that pulls this information:
$response = curl_exec($session);
$info = curl_getinfo($session);
$body = substr($response, $info['header_size']);
$decoded_result = json_decode($body, true);
I thought that json_decode would print it in the same format but clearly that's not the case. I tried json_encode but that just prints an enormous block of completely illegible information.
Is there any way to print this information in the same format that the first script returns so I can compare the two? Thanks!
This is the main purpose of json_decode: take a string in JSON format and convert it to either a PHP array or PHP StdClass object, so I'm not sure what your issue is exactly.
From your question, I think what you're trying to do is (in PHP) fetch results from some service, then fetch results from your Python script and compare the two. You should json_decode both results and then you have two neat PHP arrays that are easily traverseable in order to perform your comparison rather than two strings that would be extremely difficult to compare as such.
Think of json_decode as PHP's equivalent to Python's json.load
json_decode will take your raw JSON string and convert it into a data structure that your program understands. This is going to look different between Python and PHP.
What will look identical is the JSON-encoded string that's passed from Python to PHP. That's a universal text format. Just print it out directly, instead of using json_decode or json_encode first, and it should look closer to what you're expecting. However, it's not going to be nearly as easy to parse this way. You should think about how you plan to compare the data and see what makes the most sense logically.

Better data structure or algorithm than iterative searching on multidimensional arrays to find corresponding values?

For a site I am working on I use a library to get a list of states. It returns a numerically indexed array of states, each with three keys: stateCode, stateName, and stateSeg. It looks like this:
array
0 => &
array
'stateCode' => string 'AL' (length=2)
'stateName' => string 'Alabama' (length=7)
'stateSeg' => string 'alabama-al' (length=10)
1 => &
array
'stateCode' => string 'AK' (length=2)
'stateName' => string 'Alaska' (length=6)
'stateSeg' => string 'alaska-ak' (length=9)
2 => &
array
'stateCode' => string 'AZ' (length=2)
'stateName' => string 'Arizona' (length=7)
'stateSeg' => string 'arizona-az' (length=10)
I often find myself with one of the three values and needing to look up its corresponding value. To do this I find myself constantly having to iterate through the array of states to find the data I need. Like this:
foreach ($this->data['stateList'] as $state)
{
if ($state['stateCode'] == $searchParams['state'])
{
$stateSeg = $state['stateSeg'];
break;
}
}
$url = BASEURL . '/' . $stateSeg . ".html";
This seems inefficient to me. I think the most efficient solution I’ve been able to come up with is to turn states into objects and put them in array with multiple keys for stateCode, stateSeg, and stateName each pointing to the same state object, so they can be referenced like this:
stateList[‘CA’]->getStateSeg();
or
stateList[‘Arizona’]->getStateCode();
or
stateList[‘alaska-ak’]->getStateName();
etc…
This also seems like kind of a hack which would result in a rather large array (150 keys pointing to 50 objects) with replicated data (keys replicating data stored within objects).
Anyway, just thought I’d see if there is some kind of pattern for this type of problem. This array of states isn't the only thing I’ve come across where I’ve had to do this sort of iterative searching on multidimensional arrays to find corresponding values.
Question is tagged PHP and the code above is in PHP, but I am interested in elegant solutions in any language.
If php supports references and I know the state, I'd just pass a reference to the appropriate array element and extract from it the necessary field.
Alternatively, if you never know in advance what state you can get, create and use a map (associative container/array), let its efficient implementation take care of quickly finding whatever you need. Seems like you may need several of them.
Also, I wonder if you could get rid of everything except the "alaska-ak" strings. The data appears highly redundant.
I think your basic idea with the object and the arrays is not that bad, but instead of creating actually objects, I would just refer to the existing objects (better: array data). Let's see your original list again:
array
0 => &
array
'stateCode' => string 'AL' (length=2)
'stateName' => string 'Alabama' (length=7)
'stateSeg' => string 'alabama-al' (length=10)
1 => &
array
'stateCode' => string 'AK' (length=2)
'stateName' => string 'Alaska' (length=6)
'stateSeg' => string 'alaska-ak' (length=9)
2 => &
...
Each state object has an identifier, the array key: 0, 1, 2, ... .
All you need to do is to create three indexes based on key. You use the value as key (e.g. "AL" for "stateCode" index) and as value you take the array index, 0:
$indexStateCode['AL'] = 0;
You can then already look this up quickly:
$states[$indexStateCode['AL']];
Encapsulate this into a class with ArrayAccess and then on request instantiate the state object. You don't need it earlier.
Could you store the states in a mysql/sqlite table and use the database engine to do the lookup?
This seems inefficient to me
It isn't. Even worse-case, iterating through 50 items is probably an order of magnitude faster than querying a db.
a library to get a list of states
Not sure why you'd need a library to do this. But I'd either change the library to return the array how you need it, or wrap it in another module.
The data is somewhat redundant... All you need is two items: the state code and the state name. You can construct the "state seg" from those two. So keep a state code map and a state name map.

Need to run GET type operations on a string. Regex?

am working on some API stuff. I can pass some GET data "opt" to an application and on save in the application, the data "opt" is returned in POST. All good.
I need to pass more data to this api and I want to secure it slightly, so I have built a string containing several parts and encoded into base64.
unencoded string would look like this sec_key=xxxxx&url=../dffd/dfg/dfg.jpg&key=xxxxxx
if needed I can easily change that to:
sec_key=xxxxx&url=../dffd/dfg/dfg.jpg&key=xxxxxx
on save in the API app, I receive my encoded string back, then decode - all good.
Question is, I would usually use $_GET to strip out each data part. Can I use $_GET in some way to read from a $string rather than the url?
or do I need some regex and preg_match?. If so, whats the regex to mimic $_GET data extraction..
If you want to extract some data from a string that contains something that looks like a query string, you'll want to take a look at parse_str().
For example, the following portion of code :
$string = 'sec_key=xxxxx&url=../dffd/dfg/dfg.jpg&key=xxxxxx';
parse_str($string, $data);
var_dump($data);
Would get you :
array
'sec_key' => string 'xxxxx' (length=5)
'url' => string '../dffd/dfg/dfg.jpg' (length=19)
'key' => string 'xxxxxx' (length=6)
If needed, you could also use $_GET instead of $data, when calling parse_str().
It doesn't look like quite a good practice... But it'll work.

PHP String Split

I need to split a string into chunks of 2,2,3,3 characters and was able to do so in Perl by using unpack:
unpack("A2A2A3A3", 'thisisloremipsum');
However the same function does not work in PHP, it gives this output:
Array
(
[A2A3A3] => th
)
How can I do this by using unpack? I don't want to write a function for it, it should be possible with unpack but how?
Thanks in advance,
Quoting the manual page of unpack :
unpack() works slightly different
from Perl as the unpacked data is
stored in an associative array.
To accomplish this you have to
name the different format codes and separate them by a slash /.
Which means that, using something like this :
$a = unpack("A2first/A2second/A3third/A3fourth", 'thisisloremipsum');
var_dump($a);
You'll get the following output :
array
'first' => string 'th' (length=2)
'second' => string 'is' (length=2)
'third' => string 'isl' (length=3)
'fourth' => string 'ore' (length=3)
I've never used this function, but according to the documentation, the A character means "SPACE-padded string". So I'd hazard a guess that it's only taking the first two characters of the first word.
Have you tried unpack("A2A2A3A3", 'this is lorem ipsum'); ?

Don't understand serialize()

I'm looking at this function: serialize() for PHP and I don't really understand what is it's function. Can someone provide a simple example with output?
Basically, the goal of serialize is to transform any (alsmost) kind of data to a string, so it can be transmitted, stored, ...
A quick example :
$my_array = array(
'a' => 10,
'glop' => array('test', 'blah'),
);
$serialized = serialize($my_array);
echo $serialized;
Will get you this output :
a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}
And, later, you can unserialize that string, to get the original data back :
$serialized = 'a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}';
$data = unserialize($serialized);
var_dump($data);
Will get you :
array
'a' => int 10
'glop' =>
array
0 => string 'test' (length=4)
1 => string 'blah' (length=4)
Common uses include :
Ability to transmit (almost) any kind of PHP data from one PHP script to another
Ability to store (almost) any kind of PHP data in a single database field -- even if it's not quite a good practice on the database-side, it can sometimes be usefull
Ability to store data in some caching mecanism (APC, memcached, files, ...), in which you can only store strings
Note, though, that using serialize is great when you are only working with PHP (as it's a PHP-specific format, that's able to work with almost any kind of PHP data, and is really fast) ; but it's not that great when you have to also work with something else than PHP (as it's PHP-specific). In those cases, you can use XML, JSON (see json_encode and json_decode), ...
In the PHP manual, you can also read the Object Serialization section, btw.
If you want to save an array or object normalised in a database row for example, serialize() (and unserialize()) are your friends, because you can't store an array or object flattened without first turning it into a string.
json_encode() and json_decode() are similar except they encode as JSON.
See this example, should be pretty clear.

Categories