0% found this document useful (0 votes)
8 views

Unit - 4 Notes

mdmd,s

Uploaded by

iamjuhirathor
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit - 4 Notes

mdmd,s

Uploaded by

iamjuhirathor
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

What is XML?

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.

Key Uses of XML

1. Data Storage and Representation


XML provides a structured way to store and represent data, making it ideal for
configuration files, logs, and databases. It preserves data in a platform-independent,
hierarchical format.

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.

7. Content Management Systems (CMS)


XML is used in CMS platforms to organize and store structured content for websites and
other digital platforms.

Key Components of XML

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 &amp; Exit</note>

9. Schema/DTD (Document Type Definition)


XML schema or DTD defines the structure, constraints, and data types for an XML
document.
Example of DTD:

xml
Copy code
<!DOCTYPE note [
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
]>

Advantages of XML

• Platform-Independent: Enables seamless data sharing across platforms and


technologies.
• Human and Machine Readable: Easy to understand and parse.
• Extensible: Allows creation of custom tags.
• Structured and Hierarchical: Represents data in a tree structure.

Document Type Definition (DTD) in 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.

Key Features of DTD

1. Validation: Ensures the XML document adheres to a defined structure.


2. Structure Definition: Defines elements, attributes, entities, and notations in XML.
3. Portability: Can be internal (within the XML file) or external (stored in a separate file).
4. Readability: Helps in understanding the data format and relationships.
Introduction to PHP

PHP (Hypertext Preprocessor) is a widely-used, open-source scripting language designed for


web development and embedded in HTML. It is server-side, meaning scripts are executed on the
server, and the output is sent to the browser.

Basic Syntax

• PHP code is enclosed within <?php ... ?> tags.


• Statements end with a semicolon ;.
• Variables begin with $.

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.

Decision Making in PHP

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

PHP supports indexed, associative, and multidimensional 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

PHP allows defining custom functions.

Example
php
Copy code
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice"); // Outputs: Hello, Alice!
?>

Strings

PHP provides numerous functions to manipulate strings.

Example
php
Copy code
<?php
$text = "Hello, PHP!";
echo strlen($text); // Outputs: 11
echo strtoupper($text); // Outputs: HELLO, PHP!
?>

Form Processing

PHP handles form data using $_GET or $_POST.


HTML Form
html
Copy code
<form method="POST" action="process.php">
Name: <input type="text" name="name">
<button type="submit">Submit</button>
</form>
Processing the Form
php
Copy code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo "Hello, $name!";
}
?>

File Handling

PHP can read, write, and manage files.

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

Cookies are used to store user data on the client side.

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

Sessions store data across multiple pages on the server side.

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();
?>

Decision Making in PHP

PHP provides conditional statements to execute different blocks of code based on conditions.

1. If Statement

Executes a block of code only if a specified condition evaluates to true.

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

A shorthand for if-else statements.

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: Arrays with numeric keys.


2. Associative Arrays: Arrays with named keys.
3. Multidimensional Arrays: Arrays containing one or more arrays.

1. Indexed Arrays

Definition: Arrays with keys starting from 0 (default).

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

Definition: Arrays with custom keys (strings).

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

Definition: Arrays containing arrays as elements.

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.

Types of Functions in PHP

1. User-Defined Functions: Created by the user to perform custom tasks.


2. Built-In Functions: Predefined by PHP for common tasks like string manipulation, array handling,
etc.

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.

Creating Strings in PHP

Strings can be created using two types of quotes:

1. Single-Quoted Strings ('):


o Special characters (like \n for newlines or \t for tabs) are not interpreted inside single-
quoted strings.
o Variables are not parsed inside single-quoted strings.

Example:

php
Copy code
$name = 'Alice';
echo 'Hello, $name'; // Outputs: Hello, $name

2. Double-Quoted Strings ("):


o Special characters like \n, \t, and others are interpreted.
o Variables are parsed inside double-quoted strings.

Example:

php
Copy code
$name = 'Alice';
echo "Hello, $name"; // Outputs: Hello, Alice

String Operations

1. String Concatenation

Concatenation is the process of joining two or more strings.

• Use the . (dot) operator for concatenation in PHP.

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

To find the length of a string, use the strlen() function.

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

To replace all occurrences of a substring in a string, use the str_replace() function.

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

To extract a portion of a string, use the substr() function.

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
?>

6. String Case Conversion

PHP provides several functions for converting string cases:

• strtolower(): Converts a string to lowercase.


• strtoupper(): Converts a string to uppercase.
• ucfirst(): Capitalizes the first letter of a string.
• ucwords(): Capitalizes the first letter of each word in a string.

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!
?>

10. Comparing Strings

To compare two strings, use:

• strcmp(): Compares two strings (case-sensitive).


• strcasecmp(): Compares two strings (case-insensitive).

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

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);

• $filename: Path to the file (relative or absolute).


• $mode: Mode in which the file is opened (read, write, append, etc.).

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.

Example (Opening a file for reading):


php
Copy code
<?php
$file = fopen("example.txt", "r"); // Open file for reading
if ($file) {
echo "File opened successfully!";
} else {
echo "Failed to open the file.";
}
fclose($file); // Close the file after use
?>

Reading Files

PHP offers several functions to read files:

1. fgets(): Reads a single line from a file.


2. fread(): Reads the entire file or a specified number of bytes.
3. file_get_contents(): Reads the entire content of a file into a string.

Example (Reading a file line by line using fgets()):


php
Copy code
<?php
$file = fopen("example.txt", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line . "<br>"; // Output each line
}
fclose($file);
} else {
echo "Error opening the file.";
}
?>
Example (Reading the entire file using file_get_contents()):
php
Copy code
<?php
$file_content = file_get_contents("example.txt");
echo $file_content; // Output the entire file content
?>

Writing to Files

PHP allows you to write data to files using functions like fwrite() and file_put_contents().

1. fwrite(): Writes to an open file.


2. file_put_contents(): Writes data to a file (overwrites the file if it exists, or creates a new
file).

Example (Writing to a file using fwrite()):


php
Copy code
<?php
$file = fopen("example.txt", "w"); // Open file for writing
if ($file) {
fwrite($file, "Hello, world! This is a test.");
fclose($file);
echo "Data written to the file.";
} else {
echo "Failed to open the file.";
}
?>
Example (Using file_put_contents()):
php
Copy code
<?php
file_put_contents("example.txt", "This is some text data.");
echo "Data written to the file.";
?>

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.

Example (Closing a file):


php
Copy code
<?php
$file = fopen("example.txt", "r");
if ($file) {
// Perform operations
fclose($file); // Close the file after use
} else {
echo "Error opening the file.";
}
?>

Cookies and Sessions in PHP

Cookies and sessions are used to store information for web applications. The main difference
between them is where the data is stored:

• Cookies store data on the client-side (browser).


• Sessions store data on the server-side.

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);

• name: Name of the cookie.


• value: Value of the cookie.
• expire: Expiry time (in seconds).
• path: Path where the cookie is valid (default is /).
• domain: Domain the cookie is valid for.
• secure: Whether the cookie should only be sent over HTTPS.
• httponly: Whether the cookie is accessible only via HTTP (not JavaScript).

Example (Setting a cookie):


php
Copy code
<?php
// Set a cookie valid for 1 hour
setcookie("username", "JohnDoe", time() + 3600, "/");

echo "Cookie has been set!";


?>

Retrieving a Cookie

You can access a cookie using the $_COOKIE superglobal array.

Example (Retrieving a cookie):


php
Copy code
<?php
if (isset($_COOKIE["username"])) {
echo "Username: " . $_COOKIE["username"];
} else {
echo "No cookie found!";
}
?>

Deleting a Cookie

To delete a cookie, set its expiry time to a past date.

Example (Deleting a cookie):


php
Copy code
<?php
setcookie("username", "", time() - 3600, "/"); // Expiry time in the past
echo "Cookie has been deleted!";
?>
Sessions in PHP

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

// Set session variables


$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "[email protected]";

echo "Session variables are set.";


?>

Accessing Session Variables

You can access session variables using the $_SESSION superglobal array.

Example (Accessing session variables):


php
Copy code
<?php
session_start(); // Start the session

if (isset($_SESSION["username"])) {
echo "Username: " . $_SESSION["username"];
} else {
echo "No session data found!";
}
?>

Deleting Session Variables

To delete a specific session variable, use the unset() function.


Example (Deleting a session variable):
php
Copy code
<?php
session_start();
unset($_SESSION["username"]); // Remove the "username" session variable
echo "Session variable 'username' has been removed.";
?>

Destroying a Session

To completely destroy a session, use the session_destroy() function.

Example (Destroying a session):


php
Copy code
<?php
session_start();
session_destroy(); // Destroy all session data
echo "Session destroyed.";
?>

You might also like