1

Hii I am working with angular2 and php. In my project I want to post the json into the php page , and access it in the server side . How can I make it possible??

in my angular2 , when I click on the button SaveData() will called.

SaveData()
    {
      const headers = new Headers();
      headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');      
      let body = JSON.stringify(this.Cost);
      this.http.post('http://192.168.0.100:80/php/test.php',body,{headers})
      .subscribe(
        data => console.log('Received:' + data),
        err => console.log(err),
        () => console.log('Call Complete')
      ); 
    }

an in my PHP page I used like..

<?php

header('Access-Control-Allow-Origin: *'); 
header('Content-Type: application/json'); 
$post = $_POST['body'];
$fp = fopen('a.txt', 'w');
fwrite($fp,$post);
fclose($fp);

?>

What is the best solution for this??

1 Answer 1

2

When you post json data you can retrieve it manually using

 $post = json_decode(file_get_contents("php://input"),true);

the above line will return you the posted json data in array format.

if you want to check what is posted then you can use

print_r($post);

To save json in file modify the code as below

$post = file_get_contents("php://input");
$fp = fopen('a.json', 'w');
fwrite($fp,$post);
fclose($fp);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for Your time@Gautam. My posting data is a json String . I want to save it as a json file . Is it possible ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.