Unserialize PHP serialized data in T-SQL

后端 未结 2 398
旧巷少年郎
旧巷少年郎 2021-01-12 21:20

I am trying to extract a gift card code from a Magento order. Some other code uses the Magento API to retrieve the order info as XML from Magento and insert the XML into a M

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-12 22:19

    Here is another MSSQL function you could use to extract the value of the first instance of a token from a PHP serialized string, which are commonly found in Magento's database. The function accepts the attribute name for the value you want to extract, and the serialized value you want to parse it from:

    CREATE FUNCTION extractValueFromSerializedPhpString(
        @attribute_name nvarchar(100), @serialized_value nvarchar(max)
    ) RETURNS nvarchar(1024)
    BEGIN
        DECLARE @attribute_value_length int, @attribute_value_length_string nvarchar(5)
        SELECT @attribute_value_length_string = REPLACE(REPLACE(SUBSTRING(@serialized_value,CHARINDEX(@attribute_name,@serialized_value)+LEN(@attribute_name)+4,3),':',''),'"','')
        IF ISNUMERIC(@attribute_value_length_string) = 1 BEGIN
            SELECT @attribute_value_length = CAST(@attribute_value_length_string AS int)
            RETURN SUBSTRING(@serialized_value,CHARINDEX(@attribute_name,@serialized_value)+LEN(@attribute_name)+CASE WHEN @attribute_value_length > 99 THEN 9 WHEN @attribute_value_length > 9 THEN 8 ELSE 7 END,@attribute_value_length)
        END
        RETURN NULL
    END
    

    Note that this will only work for string values with lengths from 1 to 999 and probably has all sorts of other annoying edge cases too, but it worked for my (simple) purposes.

提交回复
热议问题