1

One of my team member has saved the object in Mysql database. I need to extract the object properties values. When I am trying to fetch it from Mysql using PHP, I am getting this as string. And no luck of accessing the property directly except an idea of using PHP substr() function.

Is there any option to convert the below string saved in database to object again so that I can access the property of it.

stdClass Object
(
[status] => 0
[environment] => Sandbox
[receipt] => stdClass Object
    (
        [quantity] => 1
        [expires_date] => 2017-04-18 08:56:57 Etc/GMT
        [is_trial_period] => false
        [purchase_date] => 2017-04-18 08:51:57 Etc/GMT
        [product_id] => com.1monthAuto.baseball
        [original_purchase_date_pst] => 2017-04-18 01:51:58 America/Los_Angeles
        [original_purchase_date_ms] => 1492505518000
        [web_order_line_item_id] => 1000000034854560
        [original_purchase_date] => 2017-04-18 08:51:58 Etc/GMT
    )

[latest_receipt] => MIIT6wYJKoZIhvcNAQcCoIIT3DCCE9gC
)
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
Arun Jain
  • 5,476
  • 2
  • 31
  • 52
  • 1
    which property you want to access? – Sahil Gulati Apr 20 '17 at 14:51
  • I want to access `latest_receipt`. – Arun Jain Apr 20 '17 at 14:52
  • 3
    Storing objects in databases sounds like a terrible designpattern to me, because it will lead to issues like this. – Qirel Apr 20 '17 at 14:52
  • 3
    Are you sure that's literally the string? So somebody is storing output from `print_r` in the database? That's awful. Anyway.. time for you to learn how to write a parser, and maybe some regex. I don't think anyone will straight up write it for you. – Evert Apr 20 '17 at 14:52
  • http://stackoverflow.com/questions/7025909/how-create-an-array-from-the-output-of-an-array-printed-with-print-r – splash58 Apr 20 '17 at 14:52
  • Is there any better idea to access latest_receipt. As the data is big, This would not be feasible to change the store logic right now. – Arun Jain Apr 20 '17 at 14:53
  • did you try `unserialize($field_from_db)` ? – Alex Slipknot Apr 20 '17 at 14:53
  • Yes I tried unserialize, but the literal text is saved as shown above. So no luck yet. – Arun Jain Apr 20 '17 at 14:54
  • `/\[latest_receipt\] => ([^\s]+)/` – splash58 Apr 20 '17 at 14:55
  • 1
    [Garbage in, garbage out.](https://en.wikipedia.org/wiki/Garbage_in,_garbage_out) ;-) You should `json_encode` the data before saving or something like this. Or write a parser and get potentially inconsistent results. – Marijan Apr 20 '17 at 14:56
  • https://blog.nixarsoft.com/2021/04/16/convert-print_r-result-to-json/ – kodmanyagha Apr 16 '21 at 14:48

2 Answers2

5

Try this hope this will help you out.

Regex: /latest_receipt\]\s*=>\s*\K[^\s\)]+/

latest_receipt\]\s*=>\s* this will match latest_receipt]spaces=>spaces

\K will reset previous match

[^\s\)]+ this will match all except space(\s) and )

Try this code snippet here

<?php

ini_set('display_errors', 1);
$string='stdClass Object
(
[status] => 0
[environment] => Sandbox
[receipt] => stdClass Object
    (
        [quantity] => 1
        [expires_date] => 2017-04-18 08:56:57 Etc/GMT
        [is_trial_period] => false
        [purchase_date] => 2017-04-18 08:51:57 Etc/GMT
        [product_id] => com.1monthAuto.baseball
        [original_purchase_date_pst] => 2017-04-18 01:51:58 America/Los_Angeles
        [original_purchase_date_ms] => 1492505518000
        [web_order_line_item_id] => 1000000034854560
        [original_purchase_date] => 2017-04-18 08:51:58 Etc/GMT
    )

[latest_receipt] => MIIT6wYJKoZIhvcNAQcCoIIT3DCCE9gC
)';
preg_match("/latest_receipt\]\s*=>\s*\K[^\s\)]+/", $string,$matches);
print_r($matches);

Solution 2: or you can Try this library //this solution will convert print_r to json, and work surely.

Try this code snippet here(Copy paste below code and check)

<?php
ini_set('display_errors', 1);
/**
 * @author Sahil Gulati <sahil.gulati1991@outlook.com> 
 */
echo printr_source_to_json(
        print_r(
                array("Name"=>"Sahil Gulati",
                      "Education"=>array(
                          "From"=>array(
                              "DU"=>array(
                                  "Course"=>"B.Sc. (Hons.) Computer Science.")
                              )
                          )
                    )
                , true
                )
        );
/**
 * This function will convert output string of `print_r($array)` to `json string`
 * @note Exceptions are always there i tried myself best to get it done. Here $array can be array of arrays or arrays of objects or both
 * @param String $string This will contain the output of `print_r($array)` (which user will get from ctrl+u of browser),
 * @return String
 */
function printr_source_to_json($string)
{
    /**
     *replacing `stdClass Objects (` to  `{`
     */
    $string = preg_replace("/stdClass Object\s*\(/s", '{  ', $string);

    /**
     *replacing `Array (` to  `{`
     */
    $string = preg_replace("/Array\s*\(/s", '{  ', $string);
    /**
     *replacing `)\n` to  `},\n`
     * @note This might append , at the last of string as well 
     * which we will trim later on.
     */
    $string = preg_replace("/\)\n/", "},\n", $string);

    /**
     *replacing `)` to  `}` at the last of string
     */
    $string = preg_replace("/\)$/", '}', $string);
    /**
     *replacing `[ somevalue ]` to "somevalue"
     */
    $string = preg_replace("/\[\s*([^\s\]]+)\s*\](?=\s*\=>)/", '"\1" ', $string);
    /**
     * replacing `=> {`  to `: {`
     */
    $string = preg_replace("/=>\s*{/", ': {', $string);
    /**
     * replacing empty last values of array special case `=> \n }` to : "" \n
     */
    $string = preg_replace("/=>\s*[\n\s]*\}/s", ":\"\"\n}", $string);

    /**
     * replacing `=> somevalue`  to `: "somevalue",` 
     */
    $string = preg_replace("/=>\s*([^\n\"]*)/", ':"\1",', $string);
    /**
     * replacing last mistakes `, }` to `}` 
     */
    $string = preg_replace("/,\s*}/s", '}', $string);
    /**
     * replacing `} ,` at the end to `}`
     */
    return $string = preg_replace("/}\s*,$/s", '}', $string);
}
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
  • +1 This seems a better idea to extract the value. Is there any option available to make this string to object so that I can extract other property values as well? – Arun Jain Apr 20 '17 at 15:03
  • @ArunJain I created a new solution which i am going to post hope it will help you out – Sahil Gulati Apr 20 '17 at 15:40
0

Using a regex and str_replace to have the latest_receipt content as a string :

$dictionary="stdClass Object
    (
    [status] => 0
    [environment] => Sandbox
    [receipt] => stdClass Object
        (
            [quantity] => 1
            [expires_date] => 2017-04-18 08:56:57 Etc/GMT
            [is_trial_period] => false
            [purchase_date] => 2017-04-18 08:51:57 Etc/GMT
            [product_id] => com.1monthAuto.baseball
            [original_purchase_date_pst] => 2017-04-18 01:51:58 America/Los_Angeles
            [original_purchase_date_ms] => 1492505518000
            [web_order_line_item_id] => 1000000034854560
            original_purchase_date] => 2017-04-18 08:51:58 Etc/GMT
        )

    [latest_receipt] => MIIT6wYJKoZIhvcNAQcCoIIT3DCCE9gC
    )";
preg_match('/.*\[latest_receipt\].*$/m', $dictionary, $matches);
$receipt = str_replace('[latest_receipt] => ', '', $matches[0]);
echo $receipt;

You can make it a function and replace latest_receipt with a variable to extract your other data.

But you should really think about storing it as a json object or to create new columns to store this data..

Lou
  • 866
  • 5
  • 14