Parsing json like data using php - 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.

Related

PHP: Merge multiple JSON encoded lines

When users keep interacting with my web app, the pages keep doing calls so that some info can be stored in a cookie linked file that is stored on the server (with the PHP session file, it gets complex: I don't have choice to see a complete history, etc.)
So, anyway, with every ajax call, I create json_encoded data in a flat file with the unique cookie name.
Data example of one such cookie file: (keys/values may repeat)
{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}
Now, when I am searching this file, to retrieve data and to do other stuff, I would like to have the entire contents in one big array as if the entire data ws json_encoded in one shot.
How do I do this? I could do a bunch of str_replace and replace the "{" and "}" and get rid of the carriage returns but that seems to be a bit ugly
Is there a better way?
Thanks
I suggest to fix your json format by using str_replace as you saying because this is the only way to have a valid json format on using this function:
$str = '{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}';
$fix_json = "[" . str_replace("}\n{", "},{", $str) . "]";
and after this you can decode you json and convert it with json_decode, like this:
$dataArray = json_decode($fix_json, true);

REST service consume with PHP 7

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];

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 />';
}

is it possible to receive only partial results in JSON from API calls using PHP?

I have been using PHP to call an API and retrieve a set of data in JSON.I need to make 20 batch calls at once. Therefore, speed is very important.
However, I only need the first element, in fact, I only need one data which is right at the beginning of the JSON file, index 0. However, the JSON file returns about 300 sets of data. I have to wait until all the data are ready before I can proceed.
I want to speed up my API calls by eliminating redundant datasets. Is it possible for me to receive the first set of the data only without having to wait until everything is ready and then go indexing the first element?
excuse my english...thank you in advance.
you could use fopen to get the bytes that are guaranteed to have what you need in it and then use regex to parse it. something like:
$max_bytes = 512;
$fp = fopen($url, "r") ;
$data = "" ;
if($fp) {
while(!preg_match('/"totalAmount"\:"(.*)"/U', $data, $match))
$data .= stream_get_contents($fp, $max_bytes) ;
fclose($fp);
if(count($match)){
$totalAmount = $match[1];
}
}
keep in mind that you cant use the string stored in $data as valid json. It will only be partial
no. json is not a "streamable" format. until you receive the whole string, it cannot be decoded into a native structure. if you KNOW what you need, then you could use string operations to retrieve the portion you need, but that's not reliable nor advisable. Similarly, php will not stream out the text as it's encoded.
e.g. consider a case where your data structure is a LOOOONG shallow array
$x = array(
0 => blah
1 => blah
...
999,999,998 => blah
999,999,999 => array( .... even more nested data here ...)
);
a streaming format would dribble this out as
['blah', 'blah' ............
you could assume that there's nothing but those 'blah' at the top level and output a ], to produce a complete json string:
['blah'.... , 'blah']
and send that, but then you continue encoding and reach that sub array... now you've suddenly got
['blah' ....., 'blah'][ ...sub array here ....]
and now it's no longer valid JSON.
So basically, json encoding is done in one (long) shot, and not in dibs and drabs, just because you simply cannot know what's coming "later" without parseing the whole structure first.
No. You need to fetch the whole set before parsing and sending the data you need back to the client machine.

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