string - PHP str_replace exceptions
I have some customer data that i convert from CSV to json using a php script.
once converted the data is all jumbled together, like this:
[{"Customer Number":"12345","Customer Name":"customer 1","Address Code":"PRIMARY","Salesperson ID":"aa","Ship to Address 1":"12345","Ship to Address 2":"123, fake street","Ship to Address 3":"","Ship to City":"Toronto","Ship to Province":"ONTARIO","Ship to Postal Code":"A1A 1A1","Country Code":"CA","Ship to Country":"CANADA","Ship to Contact Person":"John Doe","Ship to Phone":"416-555-5555","Ship to Fax":"416-555-5552","Shipping Method":"OUR TRUCK","Bill to Address 1":"12345","Bill to Address 2":"123, fake street","Bill to Address 3":"","Bill to City":"Toronto","Bill to Province":"ONTARIO","Bill to Postal Code":"A1A 1A1","Bill to Phone":"416-555-5555","Tax Schedule ID":"HST ON/S","Location Code":"TOR","Payment Terms ID":"30 DAYS PD CHEQUE","Credit Limit Amount":"2,000.00","Comment1":"30D PDC /10/11-NSF=WR BK ACCT","Comment2":"","Hold":"1","Price List":"EASTGEN"}]
.
I then use some str_replace to organize the output and make the it look nice. here's what i have:
$newArray = str_replace(":",": ",json_encode($newArray));
$newArray = str_replace("[","[\n",$newArray);
$newArray = str_replace("{","{\n",$newArray);
$newArray = str_replace(",",",\n",$newArray);
$newArray = str_replace("},","\n},",$newArray);
$newArray = nl2br($newArray);
.
the problem i'm having is that the output appears like this:
[
{
"Customer Number": "12345",
"Customer Name": "customer 1",
"Address Code": "PRIMARY",
"Salesperson ID": "aa",
"Ship to Address 1": "12345",
"Ship to Address 2": "123,
fake street",
"Ship to Address 3": "",
"Ship to City": "Toronto",
"Ship to Province": "ONTARIO",
"Ship to Postal Code": "A1A 1A1",
"Country Code": "CA",
"Ship to Country": "CANADA",
"Ship to Contact Person": "John Doe",
"Ship to Phone": "416-555-5555",
"Ship to Fax": "416-555-5552",
"Shipping Method": "OUR TRUCK",
"Bill to Address 1": "12345",
"Bill to Address 2": "123,
fake street",
"Bill to Address 3": "",
"Bill to City": "Toronto",
"Bill to Province": "ONTARIO",
"Bill to Postal Code": "A1A 1A1",
"Bill to Phone": "416-555-5555",
"Tax Schedule ID": "HST ON/S",
"Location Code": "TOR",
"Payment Terms ID": "30 DAYS PD CHEQUE",
"Credit Limit Amount": "2,
000.00",
"Comment1": "30D PDC /10/11-NSF=WR BK ACCT",
"Comment2": "",
"Hold": "1",
"Price List": "EASTGEN"}]
Please notice Ship to Address 2 , Bill to Address 2 , and Credit Limit Amount. because of my str_replace it added a line break there. the problem is that the app i use that reads the json needs it on the same line to register properly. is there a way that i can replace the comma's with a line break UNLESS they are part of an address or another variable?
Answer
Solution:
Why are you modifying a JSON-encoded string? If you're just trying to make it look "pretty", then you should use
json_encode($str, JSON_PRETTY_PRINT)
- don't do any other modifications to the string.