How to read XML file using PHP

  1. file_to_read.xml – Data in XML format.
    <jobslist>
    	<job>
    		<title>Data Analyst</title>
    		<link><![CDATA[https://www.link.com/120/data-analyst/]]></link>
        </job>
    	<job>
    		<title>Business Support Manager</title>
    		<link><![CDATA[https://www.link.com/121/business-support-manager/]]></link>
        </job>
    	<job>
    		<title>Application Engineer</title>
    		<link><![CDATA[https://www.link.com/122/application-engineer/]]></link>
        </job>
    </jobslist>
    
  2. read_xml_file.php – A PHP file to read and print XML content.
    <?php
    $url = "https://www.link.com/file_to_read.xml";
    // Convert an XML file into a SimpleXMLElement object
    $xml = simplexml_load_file($url);
    
    foreach($xml->children() as $val) {
    	$job_url = "";
    	if ($val->link != "") {
    		// In the XML file, link is a SimpleXMLElement Object
    		// Convert SimpleXMLElement Object to array
    		$val->link = preg_replace('~//<!\[CDATA\[\s*|\s*//\]\]>~', '', $val->link);
    		$job_url_array = array((string) $val->link);
    		$job_url = $job_url_array[0];
    	}
    	
    	if ($val->title != "") {
    		// In the XML file, title is a variable
    		echo "Title: " . $val->title . "<br />";
    	}
    
    	// Output:
    	// Data Analyst
    	// Business Support Manager
    	// Application Engineer
    }
    ?>
    

Debugging in PHP

<?php
// Print all PHP errors at runtime
// These 2 lines should be placed at the start of the page
ini_set('display_errors', 'On');
error_reporting(E_ALL);

// For variables
$string = "Hello World";
echo $string; // Output: Hello World

// For array
$your_array = array("Hello", "World");
echo "<pre>"; // Pretty print
print_r($your_array); // Output: array {[0] => "Hello" [1] => "World"}
die; // Stop any recurring loop and script is stopped at this line
?>

SQL modify or replace part of column data

This is probably the fastest way to change data for multiple rows.

  1. Update column set column with the new data appending to existing data
    UPDATE table SET column = CONCAT(column, new_data) 
    WHERE column = "unique_id";
    
    /* Example: */
    UPDATE table SET URL = CONCAT(URL, ".sg") 
    WHERE column = "google.com";
    
    /* Output:
    Before query: google.com
    After query: google.com.sg */
    
  2. Update column by replacing part of the existing data
    UPDATE table SET column = REPLACE(column, existing_data, new_data) 
    WHERE column = "unique_id";
    
    /* Example: */
    UPDATE table SET URL = REPLACE(URL, "google", "wordpress") 
    WHERE column = "google.com";
    
    /* Output:
    Before query: google.com
    After query: wordpress.com */
    

REST API Call using PHP

This code is very useful for crawling websites to fetch large number of information on a regular basis. To call a REST API, you need to use PHP curl.


<?php
$page = "";
if (isset($_GET['page'])) {
    $page = "&page=" . $_GET['page'];
} 

$url = "https://change_to_website_for_crawling/api";
$api_token = "change_to_your_api_key";

function curl_get_content($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('api_key' => $api_token));
    curl_setopt($curl, CURLOPT_URL, $url); //The URL to fetch. This can also be set when initializing a session with curl_init().
  
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); //The number of seconds to wait while trying to connect.

    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header.
    curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); //To automatically set the Referer: field in requests where it follows a Location: redirect.
    curl_setopt($curl, CURLOPT_TIMEOUT, 10); //The maximum number of seconds to allow cURL functions to execute.
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); //To stop cURL from verifying the peer's certificate.

   $contents = curl_exec($curl);
   curl_close($curl);
   return $contents;
}

$api_result = curl_get_content($url."/?api_key=".$api_token."&format=json".$page);
$obj = json_decode($api_result);
$result_array = objectToArray($obj);

foreach($result_array["results"] as $data_key => $data){
   echo $data["name"] . "<br />";
}
?>

How to read JSON file using PHP

You will need 2 files:

  1. file_to_read.json – Data in JSON format.
    {
      "results": [
        {
          "id": 101,
          "title": "How to Animate to Music using Toon Boom Harmony",
          "url": "/how-to-animate-to-music-using-toon-boom-harmony/",
        },
        {
          "id": 102,
          "title": "Dynamic Simulations with Reaflflow 10",
          "url": "/dynamic-simulations-with-reaflflow-10/",
        },
        {
          "id": 103,
          "title": "Maya 3D Modelling Iconic Designs",
          "url": "/maya-3d-modelling-iconic-designs/",
        },
        {
          "id": 104,
          "title": "Learn to Model a Cartoon Car in Maya",
          "url": "/learn-to-model-a-cartoon-car-in-maya/",
        },
        {
          "id": 105,
          "title": "Learn Cinema 4D from Scratch Fast and Easy",
          "url": "/learn-3d-design-in-cinema-4d-from-scratch-fast-and-easy/",
        }
      ]
    }
    
  2. read_json_file.php – A PHP file to read and print the JSON content.
    <?php
    // For PHP 5 & above, the FILE_USE_INCLUDE_PATH constant can be used to trigger include path search
    $result = file_get_contents('file_to_read.json', FILE_USE_INCLUDE_PATH);
    $obj = json_decode($result);
    $file_content = objectToArray($obj);
    
    foreach($file_content["results"] as $key => $val){ 
        echo $val["id"] . "<br />";
        // Output:
        // 101
        // 102
        // 103
        // 104
        // 105
    }
    ?>
    

Next step of web developer

https://code.tutsplus.com/articles/the-11-phases-of-a-web-developers-career-as-illustrated-by-memes–net-30840

This is quite interesting. I am at the phase 10 of my career.

Sometimes I like doing web development, sometimes I also like doing database and back-end development.