REST service consume with PHP 7 - php

As I am new to this PHP world I require some help to consume rest request with php. What I have already achieved is to submit json thoug jquery($("#form").serialize) and read the same in php along with returning json value in the response of the server call.
But I am bit stuck when I have to read rest url parameter with php. For example in case of select by Id my client calls me with url mentioned below. Now I would like to retrieve 1 and fetch from the url. With Spring pathvariable it's easy but how I can parse this url in php.
/dummy/customer/1/fetch
Note - As of now I am not using any framework only raw php.
Any help would be appreciated. Thanks in advance.

There's a lot of different ways to do this. I'll show 2 ways.
Basic string functions
We can simply split the string on / and grab the 4th part.
$output = explode($input, '/')[3];
Regular expressions
This example of a regular expression doesn't just grab the 1, it also ensures that all the other parts in the url are what you expect. Regular expressions are harder but more versatile.
$matches = null;
$success = preg_match('#^/dummy/customer/([0-9]+)/fetch$#', $input, $matches);
if (!$success) {
throw new Exception('Unexpected format');
}
$output = $matches[1];

Related

PHP Advanced Regex Splitting

I'm facing a slight issue with an idea.
I use a chat feature within an online forum on all my computing devices. I also use it mobily, which causes slight issues of formatting, input, etc. I've had the idea to relay all the chat from a relay account to my own mobile friendly site.
I haven't started on sending messages yet, although I know how to read messages. How to output them is the issue.
I sniffed outgoing packets on my computer as the chat uses ajax. I was then able to find the following url: http://server05.ips-chat-service.com/get.php?room=xxxx&user=xxxx&access_key=xxxx
The page outputs something similar to this: ~~||~~1419344231,1,kondaxdesign,Could somebody send a quick message for me__C__ please?,,10248~~||~~1419344237,1,tom.bridges,its a iso and a vm what more do we need to know?,,10880~~||~~
That string would output this in chat: http://i.stack.imgur.com/j7CM6.png
I unfortunately don't have much knowledge on regex, or any other function that would split this. Would anybody be able to assist me on getting the 1). Name, 2). Chat Data and 3). Timestamp?
As you can see, the string is something like this: ~~||~~[timestamp],1,[name],[data],,[some integer]~~||~~
Cheers.
After reading through the string output, when somebody leaves chat, this is sent: ~~||~~1419344521,2,wegface,TIMEOUT,2_10828,0~~||~~
The beginning of the log starts with 1,224442 before the first ~~||~~.
You would first explode each record, then use str_getcsv to read the string and parse it as you want. Here is a script that does that, without any formatting on output, and I've named the variables as named in the OP that describes what they are.
I wouldn't use a regular expression to parse the string, as better functionality is available (linked above)
$string = "~~||~~1419344231,1,kondaxdesign,Could somebody send a quick message for me__C__ please?,,10248~~||~~1419344237,1,tom.bridges,its a iso and a vm what more do we need to know?,,10880~~||~~";
//Split so we have each chat record to loop around
foreach( explode("~~||~~", $string) as $segments) {
//Read the CSV properly
$chat = str_getcsv($segments);
if( count($chat) <> 6 ) { continue; } //Skip any that don't have all the data
$timestamp = $chat[0];
$name = $chat[2];
$data = $chat[3];
$some_integer = $chat[5];
echo $name .' said - '. $data .'<br />';
}

Parsing json like data using php

I have some Json like data got crawling a URL
[[["oppl.lr",[,,,,,,,,,,,[[[[[,"A Google User"]
,,,,1]
,3000,,,"Double tree was ok, it wasnt super fancy or anything. Its good for families and just relaxing by the pool. Service was good, and rooms were kept neat.","a year ago",["http://www.ma..",,1],,"","",""]
]
,["Rooms","Service","Location","Value"]
,[]
Which is impossible to parse using php json_decode() function. Is there any library or something which will allow me to convert this to a regular json so that my task will be easier ? Otherwise I know I have to write regular expression.
Thanks in advanced.
Based on your comment. Incase your data is
[["oppl.lr",[,,,,,,,,,,,[[,"A Google User"],"",""],""]]]
If you can somehow send the data to client side. Then it is a valid javascript array. Either you can process the data #client side or use
JSON.stringify([["oppl.lr",[,,,,,,,,,,,[[,"A Google User"],"",""],""]]]);
and send the data back to server as
"[["oppl.lr",[null,null,null,null,null,null,null,null,null,null,null,[[null,"A Google User"],"",""],""]]]"
Else via php you can use this function
function getValidArray($input) {
$input = str_replace(",,", ',"",', $input);
$input = str_replace(",,", ',"",', $input);
$input = str_replace("[,", '["",', $input);
return eval("return $input;");
}
You can optimize the above function as per the need.

Parsing Lucene/SOLR debug.explain.structured xml output in PHP

The default "human readable" formatting of solr's debug-mode explain feature is completely useless. You can get some structured xml output by passing debug.explain.structured=true.
However the xml it generates isn't really usable either and I need to be able to use this debugging information elsewhere in my code.
Before I re-invent the wheel, I have two questions:
1) Does anyone know of an existing PHP class (or function) that will parse this xml and turn it into a useful object? (googling didn't turn up anything obvious)
2) For those familiar with SOLR's debug mode, is there a better way to approach this than parsing the debug.explain.structured xml?
(I'm Using SOLR 3.6)
I am doing this using the solr-php-client. I do use a regular expression to parse out a specific value, but it's easy to access the debug explanation.
As an example, here is how I extract the coord value from the debug explanation:
$client = new Apache_Solr_Service($hostname, $port, $url);
$response = $client->search($q, $offset, $limit, $parameters);
$debug = reset($response['debug']['explain']); // get the first explanation
if (preg_match('#([\d\.]+) = coord\((\d+)/(\d+)\)#m', $debug, $matches)) {
$coord = floatval($matches[1]);
$overlap = intval($matches[2]); // the number of matching keywords
$max_overlap = intval($matches[3]); // the total number of keywords
}
i am having the same problem and stared a github project for parsing the solr explain into an object structure. With this library it is possible to calculate the impact of a certain field from the explain output:
https://github.com/timoschmidt/php-solr-explain

Extract keywords from referrer URL

It seems Google's URLs are structured differently these days. So it is harder to extract the referring keyword from them. Here is an example:
http://www.google.co.uk/search?q=jquery+post+output+46&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a#pq=jquery+post+output+46&hl=en&cp=30&gs_id=1v&xhr=t&q=jquery+post+output+php+not+running&pf=p&sclient=psy-ab&client=firefox-a&hs=8N5&rls=org.mozilla:en-US%3Aofficial&source=hp&pbx=1&oq=jquery+post+output+php+not+run&aq=0w&aqi=q-w1&aql=&gs_sm=&gs_upl=&bav=on.2,or.r_gc.r_pw.,cf.osb&fp=bdeb326aa44b07c5&biw=1280&bih=875
The search I performed was actually "jquery post output php not running", so the first 'q=' does not contain the full search. The second one does. I'd like to write a script that always extracts the last 'q=', but I'm not sure if Google's URL's always have the full search last. Anyone had any experience with this.
You can accomplish this using parse_url(), parse_str(), and urldecode(), where $str is the refer string:
$fragment = parse_url($str, PHP_URL_FRAGMENT);
parse_str($fragment, $arr);
$query = urldecode($arr['q']); // jquery post output php not running

Problem with php and json

Could some one please help me out on this I have the following json string
string(1223) "YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"google","Result":[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}]}})"
But I cannot seem to get anywhere with it. Basically I want to just loop out the the results which are
[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}]
Sorry my question is how can I loop or even print the first result for example
{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"}
Your string is not JSON, it is JSON-in-Script. Notice the fragment that says:
YAHOO.Finance.SymbolSuggest.ssCallback(...)
When a browser receives the above mentioned script (actually a javascript code) it will call the YAHOO.Finance.SymbolSuggest.ssCallback function, passing the JSON data as the argument.
You did not mention if you want to access the JASON data on the server side or client? It its server side (PHP) then you can use regular expressions or string replacement functions to extract the portion you like. The you can use json_decode() function to convert the resulting string into an associative array.
Edit ----
A quick and dirty hack for converting JSONP to JSON:
<?php
$text = 'YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"google","Result":[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}]}})';
# //CONVERT JSONP to JSON\\
$text = preg_replace('/.+?({.+}).+/', '$1', $text);
# \\CONVERT JSONP to JSON//
$data = json_decode($text);
var_dump($data);
var_dump($data->ResultSet->Result[0]);
var_dump($data->ResultSet->Result[0]->symbol);
var_dump($data->ResultSet->Result[0]->name);
# etc etc
?>
Your result is not just a JSON string, it's a JSON string prepended by a call to a JSON function. This is quite certainly a JSONP call.
You must write the YAHOO.Finance.SymbolSuggest.ssCallback(data) javascript function and get the Json there. Check the JSONP query, you should be able to alter the name of this backreference function if you want another name, it's usually on of the parameter in the GET query.
Now you are maybe calling it directly from PHP and you are not in js envirronment. so you must write something in your PHP code to remove the YAHOO.Finance.SymbolSuggest.ssCallback( part and the ) at the end before parsing it as JSON data..

Categories