Read and write json in php

Read json-file:

$data = file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/myfile.json");
$myArray = json_decode($data, true);

Write array to a json-file:

$jsonArray = json_encode($myArray);
file_put_contents("/myfile.json", $jsonArray);

To return json when php-file is called, simply:

echo json_encode($myArray); 

Published
Categorized as php

React fetch file with params

The URLSearchParams interface is handy when building a request.

let searchParams = new URLSearchParams(window.location.search);

Then do whatever with the parameters and do the fetch, in this case a php-file returning json-data.

let a = "https://someserver.com/somefile.php";
if (!searchParams.entries().next().done) {  
   a += "?" + searchParams;        
}
       
fetch(a)            
.then( response => { return response.json() })            
.then( json => {  
   this.setState({
      myData:json
   });
});

Published
Categorized as react

Simple workflow with jsx/babel

I currently use a primitive react/jsx-workflow based on standalone babel and manually copying code from test to production.

My sites all have separate test and production domains. I use client side react/jsx, and php for everything server side.

At the test-sites I work with jsx, this code is compilated on page load with standalone babel. To make this work you first have to include babel.min.js and then the relevant jsx-script with type=”text/babel”.

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel" src="/myscripts/myfile.jsx"></script>

When the code is ready for production I manually copy-paste the jsx into the online compilator at https://babeljs.io/repl. And then copy the result into the relevant myfile.js at the production environment.