Getting and parsing XML in PHP

If you have XML data you need to download, you can download it with file_get_contents($url), which will return file as a string. Then you use simplexml parser to parse through the XML.

You may need to add allow_url_fopen=1 to the php.ini to allow for the file download with file_get_contents.

<?php
$url = 'https://www.example.com/file.xml';
$xml_str = file_get_contents($url);
$xml_feed = simplexml_load_string($xml_str);
//then you can do a foreach on each row returned on the xml, like so..
foreach($xml_feed as $key => $data){
	
}
?>

How to POST JSON content with PHP and curl

If you need to POST json to a url with CURL and PHP, in this case making a POST to https://www.example.com this sample code should help you.

<?php				
$json_data = array(
    'field1'=>'data1',
    'field2' => 'data2');
$url = 'https://www.example.com';
$json_string = json_encode($json_data);
//curl php library
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string)
    )
);
$result = curl_exec($ch);
?>

Get JSON in POST with PHP

With PHP, you can not use $_POST variable if the content you are POSTing, is JSON. Instead, you must use a different method for getting the JSON data from the POST.

<?php
//assures the content being posted is content-type of application/json
if($_SERVER["CONTENT_TYPE"] == 'application/json')
{
$json_string = file_get_contents('php://input');
$json = json_decode($json_string);
//$json will be an object with the data that was in the POST
}
?>