Unit - 4 Notes
Unit - 4 Notes
XML (eXtensible Markup Language) is a markup language designed to store and transport data
in a structured, human-readable, and machine-readable format. Unlike HTML, XML is not
focused on displaying data but on describing it, allowing developers to define custom tags and
organize data meaningfully.
Example:
xml
Copy code
<book>
<title>Introduction to XML</title>
<author>John Doe</author>
<price>29.99</price>
</book>
2. Data Exchange
XML is widely used for transferring data between systems, applications, and platforms,
as it ensures compatibility. This is especially common in web services (e.g., SOAP) and
APIs.
Example Use: XML in RESTful APIs or message formats for communication between
syste
3. Document Structuring
XML is used to structure complex documents like books, reports, articles, or manuals.
Standards like DocBook and DITA (Darwin Information Typing Architecture) use XML
for documentation.
4. Web Development
XML is used in web technologies like XHTML for structuring web pages and SVG for
scalable vector graphics. It also supports RSS and Atom feeds for syndicating content.
Example: RSS Feed
xml
Copy code
<rss version="2.0">
<channel>
<title>My Blog</title>
<link>http://myblog.com</link>
<description>Latest posts from my blog.</description>
</channel>
</rss>
5. Interoperability
XML facilitates interoperability between different systems by providing a common
format for exchanging data. It is often used as a medium for connecting frontend and
backend systems.
6. Database Integration
XML is used for exporting, importing, and transferring data between databases. Some
databases store XML natively or use it to define schema constraints.
1. Prolog
The prolog specifies the XML version and encoding used in the document.
Example:
xml
Copy code
<?xml version="1.0" encoding="UTF-8"?>
2. Elements
Elements are the basic building blocks of XML. They contain the data or child elements
and are defined by a start and end tag.
Example:
xml
Copy code
<person>
<name>John Doe</name>
<age>30</age>
</person>
3. Attributes
Attributes provide additional information about elements and are defined within the start
tag.
Example:
xml
Copy code
<person id="101">
<name>Jane Doe</name>
</person>
4. Text
The text is the data content enclosed within XML elements.
Example:
xml
Copy code
<message>Hello, World!</message>
5. CDATA Sections
CDATA (Character Data) sections allow including special characters (like <, >, &)
without being treated as XML markup.
Example:
xml
Copy code
<script><![CDATA[
if (x < y) alert('x is less than y');
]]></script>
6. Comments
Comments in XML help annotate the document and are ignored by the parser.
Example:
xml
Copy code
<!-- This is a comment -->
7. Processing Instructions
These provide directions to the application processing the XML.
Example:
xml
Copy code
<?xml-stylesheet type="text/css" href="style.css"?>
8. Entities
Entities are placeholders for reserved or repetitive characters.
Example:
xml
Copy code
<note>Save & Exit</note>
xml
Copy code
<!DOCTYPE note [
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
]>
Advantages of XML
A Document Type Definition (DTD) is used to define the structure, elements, and attributes of
an XML document. It ensures the document's validity by providing a set of rules that XML must
follow.
Basic Syntax
Example:
php
Copy code
<?php
echo "Hello, World!";
?>
In PHP, echo is a commonly used construct for outputting text, variables, or HTML content to
the browser. It is simple and efficient for displaying content on a webpage.
PHP provides conditional statements to execute different blocks of code based on conditions.
If-Else
php
Copy code
<?php
$age = 18;
if ($age >= 18) {
echo "Eligible to vote.";
} else {
echo "Not eligible to vote.";
}
?>
Switch Case
php
Copy code
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week.";
break;
case "Friday":
echo "Almost the weekend!";
break;
default:
echo "It's a regular day.";
}
?>
Loops in PHP
For Loop
php
Copy code
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i<br>";
}
?>
While Loop
php
Copy code
<?php
$i = 1;
while ($i <= 5) {
echo "Count: $i<br>";
$i++;
}
?>
Foreach Loop (For arrays)
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
?>
Arrays
Indexed Array
php
Copy code
<?php
$colors = ["Red", "Green", "Blue"];
echo $colors[1]; // Outputs: Green
?>
Associative Array
php
Copy code
<?php
$ages = ["John" => 25, "Jane" => 22];
echo $ages["John"]; // Outputs: 25
?>
Multidimensional Array
php
Copy code
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
];
echo $matrix[1][2]; // Outputs: 6
?>
Functions
Example
php
Copy code
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice"); // Outputs: Hello, Alice!
?>
Strings
Example
php
Copy code
<?php
$text = "Hello, PHP!";
echo strlen($text); // Outputs: 11
echo strtoupper($text); // Outputs: HELLO, PHP!
?>
Form Processing
File Handling
Read a File
php
Copy code
<?php
$content = file_get_contents("example.txt");
echo $content;
?>
Write to a File
php
Copy code
<?php
file_put_contents("example.txt", "New content!");
?>
Cookies
Set a Cookie
php
Copy code
<?php
setcookie("username", "JohnDoe", time() + (86400 * 30), "/");
?>
Access a Cookie
php
Copy code
<?php
if (isset($_COOKIE["username"])) {
echo "Welcome " . $_COOKIE["username"];
}
?>
Sessions
Start a Session
php
Copy code
<?php
session_start();
$_SESSION["username"] = "JohnDoe";
?>
Access Session Data
php
Copy code
<?php
session_start();
echo "Welcome " . $_SESSION["username"];
?>
Destroy a Session
php
Copy code
<?php
session_start();
session_destroy();
?>
PHP provides conditional statements to execute different blocks of code based on conditions.
1. If Statement
Syntax:
php
Copy code
if (condition) {
// Code to execute if condition is true
}
Example:
php
Copy code
<?php
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
}
?>
2. If-Else Statement
Executes one block of code if the condition is true and another if the condition is false.
Syntax:
php
Copy code
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
php
Copy code
<?php
$marks = 40;
if ($marks >= 50) {
echo "You passed!";
} else {
echo "You failed.";
}
?>
3. If-Elseif-Else Statement
Allows multiple conditions to be checked sequentially. The first true condition's block is
executed.
Syntax:
php
Copy code
if (condition1) {
// Code if condition1 is true
} elseif (condition2) {
// Code if condition2 is true
} else {
// Code if none of the conditions are true
}
Example:
php
Copy code
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 75) {
echo "Grade: B";
} else {
echo "Grade: C";
}
?>
4. Switch Case
Efficient for checking multiple conditions that compare the same variable or expression. Each
case block ends with a break to prevent falling through.
Syntax:
php
Copy code
switch (variable) {
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
default:
// Code to execute if no cases match
}
Example:
php
Copy code
<?php
$day = "Tuesday";
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Almost the weekend!";
break;
case "Sunday":
echo "Relax, it's Sunday!";
break;
default:
echo "It's a regular weekday.";
}
?>
5. Ternary Operator
Syntax:
php
Copy code
condition ? value_if_true : value_if_false;
Example:
php
Copy code
<?php
$age = 17;
echo $age >= 18 ? "Eligible to vote" : "Not eligible to vote";
?>
Arrays in PHP
An array in PHP is a data structure that allows storing multiple values in a single variable. PHP
supports three types of arrays:
1. Indexed Arrays
Syntax:
php
Copy code
$array_name = array(value1, value2, value3); // Using array()
$array_name = [value1, value2, value3]; // Using []
Example:
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[1]; // Outputs: Banana
?>
2. Associative Arrays
Syntax:
php
Copy code
$array_name = array("key1" => value1, "key2" => value2);
$array_name = ["key1" => value1, "key2" => value2];
Example:
php
Copy code
<?php
$ages = ["John" => 25, "Jane" => 22];
echo $ages["John"]; // Outputs: 25
?>
3. Multidimensional Arrays
Syntax:
php
Copy code
$array_name = [
[value1, value2],
[value3, value4],
];
Example:
php
Copy code
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
];
echo $matrix[1][2]; // Outputs: 6
?>
Functions in PHP
A function in PHP is a block of reusable code that performs a specific task. Functions allow you
to structure your program into smaller, manageable, and reusable parts.
1. User-Defined Functions
Definition
A user-defined function is a block of code written by the user to perform a specific task. It can
accept parameters and return values.
Syntax
php
Copy code
function function_name($parameter1, $parameter2, ...) {
// Code to execute
return $value; // Optional
}
Example
php
Copy code
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice"); // Outputs: Hello, Alice!
?>
2. Built-In Functions
Commonly Used Built-In Functions
1. String Functions:
o strlen(): Returns the length of a string.
o strtolower(): Converts a string to lowercase.
o strtoupper(): Converts a string to uppercase.
o substr(): Extracts a portion of a string.
php
Copy code
<?php
echo strlen("Hello"); // Outputs: 5
?>
2. Array Functions:
o count(): Counts elements in an array.
o array_push(): Adds elements to the end of an array.
o array_merge(): Merges two or more arrays.
php
Copy code
<?php
$arr = ["Red", "Green"];
array_push($arr, "Blue");
print_r($arr); // Outputs: Array ( [0] => Red [1] => Green [2] => Blue
)
?>
3. Math Functions:
o sqrt(): Returns the square root of a number.
o rand(): Generates a random number.
o abs(): Returns the absolute value.
php
Copy code
<?php
echo sqrt(16); // Outputs: 4
?>
4. File Functions:
o fopen(): Opens a file.
o fwrite(): Writes to a file.
o fread(): Reads from a file.
php
Copy code
<?php
$file = fopen("example.txt", "r");
echo fread($file, filesize("example.txt"));
fclose($file);
?>
Strings in PHP
A string is a sequence of characters enclosed within quotes. Strings are one of the most
commonly used data types in PHP. PHP provides many functions to manipulate strings, such as
concatenation, length checking, and pattern matching.
Example:
php
Copy code
$name = 'Alice';
echo 'Hello, $name'; // Outputs: Hello, $name
Example:
php
Copy code
$name = 'Alice';
echo "Hello, $name"; // Outputs: Hello, Alice
String Operations
1. String Concatenation
Example:
php
Copy code
<?php
$first_name = "Alice";
$last_name = "Smith";
$full_name = $first_name . " " . $last_name;
echo $full_name; // Outputs: Alice Smith
?>
2. String Length
Syntax:
php
Copy code
strlen($string); // Returns the length of the string
Example:
php
Copy code
<?php
$string = "Hello, World!";
echo strlen($string); // Outputs: 13
?>
3. String Position
To find the position of the first occurrence of a substring within a string, use the strpos()
function.
Syntax:
php
Copy code
strpos($string, $substring); // Returns the position of the first occurrence
Example:
php
Copy code
<?php
$string = "Hello, World!";
$position = strpos($string, "World");
echo $position; // Outputs: 7
?>
4. String Replacement
Syntax:
php
Copy code
str_replace($search, $replace, $string);
Example:
php
Copy code
<?php
$string = "Hello, World!";
$new_string = str_replace("World", "Alice", $string);
echo $new_string; // Outputs: Hello, Alice!
?>
5. Substring
Syntax:
php
Copy code
substr($string, $start, $length); // Extracts a substring starting at $start
and of length $length
Example:
php
Copy code
<?php
$string = "Hello, World!";
$substring = substr($string, 7, 5);
echo $substring; // Outputs: World
?>
Example:
php
Copy code
<?php
$string = "hello, world!";
echo strtolower($string); // Outputs: hello, world!
echo strtoupper($string); // Outputs: HELLO, WORLD!
echo ucfirst($string); // Outputs: Hello, world!
echo ucwords($string); // Outputs: Hello, World!
?>
Example:
php
Copy code
<?php
$string1 = "hello";
$string2 = "HELLO";
echo strcmp($string1, $string2); // Outputs: non-zero (since case-sensitive
comparison)
echo strcasecmp($string1, $string2); // Outputs: 0 (since case-insensitive
comparison)
?>
File handling in PHP allows you to perform various operations on files, such as reading, writing,
appending, and modifying. PHP provides built-in functions for working with files, making it
easy to create, open, and manipulate files on the server.
Opening Files
To open a file in PHP, you can use the fopen() function. This function requires the file path and
the mode in which the file should be opened.
Syntax:
php
Copy code
$file = fopen($filename, $mode);
Modes:
• 'r': Read-only mode. The file pointer is placed at the beginning of the file.
• 'w': Write-only mode. If the file does not exist, it will be created. If it exists, it will be
overwritten.
• 'a': Append mode. If the file does not exist, it will be created. Data is written to the end of the
file.
• 'x': Write-only mode. Creates a new file. If the file already exists, the operation fails.
• 'r+': Read and write mode. The file pointer is placed at the beginning of the file.
• 'w+': Read and write mode. If the file exists, it will be overwritten.
• 'a+': Read and append mode.
Reading Files
Writing to Files
PHP allows you to write data to files using functions like fwrite() and file_put_contents().
Appending to Files
To append data to a file without overwriting the existing content, you can use the fopen()
function in append mode ('a' or 'a+').
Example (Appending data to a file):
php
Copy code
<?php
$file = fopen("example.txt", "a"); // Open file for appending
if ($file) {
fwrite($file, "\nAppended text.");
fclose($file);
echo "Data appended to the file.";
} else {
echo "Failed to open the file.";
}
?>
Closing Files
After performing any file operations, it is essential to close the file using the fclose() function.
This frees up system resources and ensures that the file is properly saved.
Cookies and sessions are used to store information for web applications. The main difference
between them is where the data is stored:
Cookies in PHP
A cookie is a small text file stored on the user's computer. PHP provides functions to set,
retrieve, and delete cookies.
Setting a Cookie
To set a cookie, use the setcookie() function.
Syntax:
php
Copy code
setcookie(name, value, expire, path, domain, secure, httponly);
Retrieving a Cookie
Deleting a Cookie
A session stores data on the server, making it more secure than cookies. Each session is
identified by a unique session ID, which is stored in a cookie on the client-side.
Starting a Session
To use sessions, call the session_start() function at the beginning of the script.
Syntax:
php
Copy code
session_start();
Example (Starting a session and setting session variables):
php
Copy code
<?php
session_start(); // Start the session
You can access session variables using the $_SESSION superglobal array.
if (isset($_SESSION["username"])) {
echo "Username: " . $_SESSION["username"];
} else {
echo "No session data found!";
}
?>
Destroying a Session