I'm currently working with an existing database that is Mysql, and the system is built in php.
For whatever reason the builder of this system chose to store some parts of the data in blobs. One of them is a tiny blob.
In the database one of the records appears like this:
a:2:{i:0;s:3:"130";i:1;s:3:"182";}
This is viewable from the sql client I'm using. It says it's a TINYBLOB(255).
I need to be able to figure out the correct structure used to set this up so that I could build my part.
It appears to me as if I'm not seeing a "true" representation of what the data structure is.
I ran this on the php side:
public function types_get() {
$returnedTypes = $this->api->getReportTypes();
echo($returnedTypes);
$this->response($returnedTypes,REST_Controller::HTTP_OK);
}
It also produced this on the echo and response: a:2:{i:0;s:3:"130";i:1;s:3:"182";}
How would I be able to make it so I can see the true data as if it was a json string?
This data string has been created with the serialize() function. You can convert it back to a native array with the matching unserialize() function:
$string = 'a:2:{i:0;s:3:"130";i:1;s:3:"182";}';
$data = unserialize($string);
print_r($data);
Output:
Array(
[0] = 130
[1] = 182
)
Related
I am trying to save the sports that a user has liked on Facebook to a database. This code is part of my Facebook login, I am using laravel.
$me contains all the user data that I receive from Facebook.
if (array_key_exists('sports', $me)){
$test = $me['sports'];
$json = strval($test); PROBLEM HERE
$data = json_decode($json, true);
$sports = array();
foreach ($data as $item) {
$sports[] = $item['name'];
}
$user->fb_sports = $sports;
}
My problem is that I am getting an array to string conversion. I am trying to convert the content of the $test variable to a string for the code that follows to work properly.
However, I don't really know what to do.
$me['sports']
returns
[{"id":"108124505876479","name":"Wakeboarding"},{"id":"112003352149145","name":"Bouldering"},{"id":"110008522357035","name":"Handball"}]
However, for my code to work properly I would need it to return this (notice the ' and ' ):
'[{"id":"108124505876479","name":"Wakeboarding"},{"id":"112003352149145","name":"Bouldering"},{"id":"110008522357035","name":"Handball"}]'
Is there any way to fix this? I simply want to save those sports to a database. Am I maybe choosing a completely wrong way here?
Any help would be much appreciated.
Thanks.
EDIT:
When I try this:
$sports = array();
foreach($me['sports'] as $sport){
// save the name i.e.
$sports[] = $sport['name'];
}
//saving array
$user->fb_sports = $sports;
I get this:
I assume you're using the PHP SDK of Facebook. This class already converts the JSON string to a PHP array. That's why "$me['sports']" is an array.
There are several options to save these sports to your database.
Do you want to save all the sports separately or all together in one string?
If you would like to save them separately you need to loop:
foreach($me['sports'] as $sport){
// save the name i.e.
your_save_function($sport['name']);
}
If you want to save all the sports together in one string I would suggest taking a look into the serialize function.
$serializedString = serialize($me['sports']);
To use the array again you need to get it from the database and unserialize it.
Another option is to convert the array to a JSON string again and save this.
$jsonString = json_encode($me['sports']);
your_save_function($jsonString);
If you want to use it as an array again you need to get it from the database and convert the JSON string to an array.
$sports = json_decode($your_db_array['sports']);
As you can see there are several ways. Maybe you can explain what you would like to do with the data as soon you saved it into the database, so I can help you choosing the best way.
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.
IP.Nexus puts custom fields into a table all muddled up into one row and some how pulls the correct data out.
basically my custom fields row looks like so:
a:2:{i:2;s:4:"Test";i:3;s:10:"Accounting";}
How do i select what item to pull as i would like to out put just one item not the whole row, is it with delimiters or string splitter, as i am novice with this part of mySQL
Cause i would like to echo out just the advertising on its own and also vice versa for the testing.
Thanks in advance
It's a serialized array using serialize() function so you can get its contents using unserialize($YourString);.
But I see that you string is corrupted for deserialization, because s:4: in s:4:"advertising" says that after s:4: 4 character long string is expected that advertising is not.
The data in the database is in serialized(json) form.You can turn it into simple array using unserialize.
For example;if $mystr is your string
write
$mystring=unserialize($mystring)
You will get normal array of this string
You can do
foreach($mystring as $str){
$ads[]=$str['advertising'];
}
and the resulting array $ads will be the ads you like in simple array form
Since this looks as JSon, you can use a PHP JSon module to parse each row from MySQL.
<?php
(...)
while (...) {
$obj = json_decode($row);
// do something with $obj
}
I need to dump an xml string (coming into a web service as a POST param), directly into a Mysql DB. The column into which I am writing is currently of type 'text', though I have tried blob as well.
Right now, when I save the string and retrieve it later on using sql, it comes back in a serialized like format, like this:
a:1:{s:14:"<?xml_encoding";s:1502:"UTF-8?><record>
<nodes></nodes>
</record>";}
Whereas, I need to parse that xml as a simplexml object, and hence need it to be better formed.
This is what I am doing codewise:
Accept Post Param in web service
Serialize and store it in DB using doctrine ORM, kind of like
$record->xml_rec = serialize($_POST)
Retrieve it and echo it.
Oddly enough, if I unserialize and echo is upon retrial, I get an array. The array looks like this upon print_f
Array
(
[<?xml_encoding] => UTF-8?><record>
<nodes></nodes>
</record>
)
Still not parse-able by simplexml.
Is this a mysql storage problem or am I doing something wrong with the POST params? I've tried htmlspecialchars to save the string in the db, but similar problems remain.
any help is appreciated, thanks
What you have is a "serialized" php array that you can unserialize by using ... PHP's unserialize function.
I have a json feed from zoho : here, you can acces the same file unencrypted here
I like to be able to display and parse the data from that feed int html
I have ask a similar question yesterday, but the solution was a javascript, and having java disable client side can lead to nothing to display... so i will go with php. I can parse a var but a feed ?....
Question #2. Is it possible to capture a json feed, and save it as file (for backup purpose), so i will acces that file if the site go down (small possibilites)
You first have to get the JSON data from the remote server ; not sure how you can do that, considering there seems to be an authentication mecanism in place, but maybe file_get_contents or curl could help.
Once you have that JSON string in a PHP variable, it's just a matter of calling json_decode on it, to get your data.
For instance :
$json = file_get_contents('http://produits-lemieux.com/json.txt');
// you can save $json to a file, if needed :
//file_put_contents('file/path/my-file.txt', $json);
$data = json_decode($json);
var_dump($data);
Will get you an output like this one :
object(stdClass)[1]
public 'Liste_des_produits1' =>
array
0 =>
object(stdClass)[2]
public 'Added_Time' => string '28-Sep-2009 16:35:03' (length=20)
public 'prod_ingredient' => string 'sgsdgds' (length=7)
public 'prod_danger' =>
array
0 => string 'sans danger pour xyz' (length=20)
....
Note I used the "not encrypted" version, because I have no idea what kind of API you need to use to access the crypted one (never used "zoho")
json_decode will convert the json string to object form by default, in order to use it as associative array you have to specify 'true' as second parameter, example below.
json_decode($json,true)
reference : php Json_decode reference
The simplified code to do what you want.
$sJson = file_get_contents('http://example.com/path/to/feed.json');
file_put_contents('/path/to/file', $sJson);
$oJson = json_decode($sJson);
var_dump($oJson);
If URL Wrappers are off or you need authentication headers (or other special headers set), use the curl libraries in place of file_get_contents.
I like to be able to print/access some variable but cannot seem to have the trick to access the array the wright way
based on the previous answer :
$json = file_get_contents('http://produits-lemieux.com/json.txt');
$data = json_decode($json);
//var_dump($data);
print_r($data['prod_ingredient']); //dont work !... error
print_r($data['Liste_des_produits1'].prod_ingredient[0]); //dont work !... error