views:

43

answers:

3

Hello,

I want split a string which consists of products. Each product is encloded within {..}, and separated by comma.

For instance, I have a strin below.

[
{\"productid\" : \"prod:kj42j3d24-47c2-234lkj2-e3c2-cfc9a4a3b005\",\"memo\" : \"
product description
\",\"taxable\" : 0,\"unitweight\" : 0,\"unitcost\" : 0,\"unitprice\" : 12.34,\"quantity\" : 1.00},
{\"productid\" : \"prod:k324jl-462d-e589-aecf-32k4j\",\"memo\" : \"
prodict description
\",\"taxable\" : 0,\"unitweight\" : 0,\"unitcost\" : 0,\"unitprice\" : 12.23,\"quantity\" : 1}
]

and want to separate each product into different indexes of an array. Thanks.

+2  A: 

Looks like JSON to me:

$a = json_decode(" [ 
  {\"productid\" : \"prod:kj42j3d24-47c2-234lkj2-e3c2-cfc9a4a3b005\",
   \"memo\" : \" product description \",\"taxable\" : 0,\"unitweight\" : 0,
   \"unitcost\" : 0,\"unitprice\" : 12.34,\"quantity\" : 1.00}, 
  {\"productid\" : \"prod:k324jl-462d-e589-aecf-32k4j\",
   \"memo\" : \" prodict description \",\"taxable\" : 0,\"unitweight\" : 0,
   \"unitcost\" : 0,\"unitprice\" : 12.23,\"quantity\" : 1} ] ", true
);
konforce
I do use json_decode() in the later step. The reason I want split it into the array is that the product description contains HTML tags, and for some reason json_decode() sometimes cannot process HTML tags properly and returns NULL. Hence the major reason is to remove the replace the HTML string with dummy string, and then replace it back after executing json_decode().
slao.it
`json_decode()` should be able to decode any valid JSON string. Perhaps you need to fix your encoding routine? Splitting up a JSON string prematurely is definitely not a good solution...
konforce
+1  A: 

your string looks a lot like a JSON-encoded array of objects. Try using the php function json_decode.

$parsed_array = json_decode($str);
Lee
I do use json_decode() in the later step. The reason I want split it into the array is that the product description contains HTML tags, and for some reason json_decode() sometimes cannot process HTML tags properly and returns NULL. Hence the major reason is to remove the replace the HTML string with dummy string, and then replace it back after executing json_decode().
slao.it
+1  A: 

In this particular case, it appears like your string is already in JSON format. PHP has inbuilt support for this. To take this string and make it a JSON object, use the json_decode function.

More information in the PHP manual here: http://www.php.net/manual/en/function.json-decode.php

kobrien