Quinten Rowland
Quinten Rowland

Reputation: 11

PHP & JSON : Trying to write JSON to Mysql

I am having an issue where my PHP script opens a file with JSON code and needs to insert it into a MySQL database.

For some reason it only displays some of the output from the JSON.

Here is my code

 $json = json_decode(file_get_contents('data.json'), true);
  $data = $json;
  // VAR's
  $system = $data['System'];
  $cid_from = $data["From"];
  $cid_to = $data['To'];

  //DEBUG USAGES
  $array = print_r($data, true);


  ////// THIS ONE WORKS FINE
  echo $data["System"];

  ////// THIS ONE DOESN'T WORK
  echo $data["To"];  

  file_put_contents('output/json-local.txt',$array . "\r\n", FILE_APPEND);

  ////// BUT HERE IT ACTUALLY WORKS
  file_put_contents('output/cli-from.txt',$data['From']. "\r\n", FILE_APPEND);
  file_put_contents('output/cli-to.txt',$data['To']. "\r\n", FILE_APPEND);
  // file_put_contents('json-sysid-local.txt',$systemid . "\r\n", FILE_APPEND);

Here is the contents of data.json

{"action":"call-data-record",
"System":"48130b83e2232f0ecd366a92d4d1261d",
"PrimaryCallID":"[email protected]_1",
"CallID":"0440b807@pbx",
"From":"<sip:[email protected]>",
"To":"<sip:[email protected]>",
"Direction":"O",
"RemoteParty":"",
"LocalParty":"",
"TrunkName":"",
"TrunkID":"",
"Cost":"",
"CMC":"",
"Domain":"xxx.co.za",
"TimeStart":"2018-08-14 16:03:21",
"TimeConnected":"",
"TimeEnd":"2018-08-14 16:03:23",
"LocalTime":"2018-08-14 18:03:21",
"DurationHHMMSS":"0:00:00",
"Duration":"0",
"RecordLocation":"",
"RecordUsers":"",
"Type":"hunt",
"Extension":"100",
"ExtensionName":"100",
"IdleDuration":"",
"RingDuration":"2",
"HoldDuration":"0",
"IvrDuration":"0",
"AccountNumber":"400",
"IPAdr":"",
"Quality":"VQSessionReport: CallTerm\r\nLocalMetrics:\r\nCallID:0440b807@pbx\r\nFromID:<sip:[email protected]>\r\nToID:<sip:[email protected]>;tag=1460166964\r\nx-UserAgent:Vodia-PBX/57.0\r\nx-SIPmetrics:SVA=RG SRD=91\r\nx-SIPterm:SDC=OK SDR=OR\r\n"}

Upvotes: 0

Views: 101

Answers (2)

Venkat D
Venkat D

Reputation: 139

The browser source clearly shows "To":"" is being written by PHP to the browser output correctly but the browser is interpreting as an HTML opening tag hence ignoring the rest of the content.

Wrap your output in the PHP htmlspecialchars() function to see the output as in the file.

Add - echo "TO : ".htmlspecialchars($data["To"]);

Upvotes: 0

Tobias K.
Tobias K.

Reputation: 3082

Your "To" data is encapsulated in <>. This causes your browser to interpret it as an HTML tag and not display any content.

You can (should!) escape the special HTML control characters:

echo htmlspecialchars($data["To"]);

See http://php.net/htmlspecialchars

Edit: It doesn't hurt to precautionary add this to your other outputs aswell. If the string doesn't contain such characters, it will simply be returned onchanged. You eliminate possible XSS attack vectors this way.

Upvotes: 1

Related Questions