来源:www.cncfan.com | 2006-1-11 | (有2604人读过)
Table of Contents solid_close solid_connect solid_exec solid_fetchrow solid_fieldname solid_fieldnum solid_freeresult solid_numfields solid_numrows solid_result The Solid functions are deprecated, you probably want to use the Unified ODBC functions instead.
solid_close solid_close -- close a Solid connection
Description See odbc_close().
solid_connect solid_connect -- connect to a Solid data source
Description See odbc_connect().
solid_exec solid_exec -- execute a Solid query
Description See odbc_exec().
solid_fetchrow solid_fetchrow -- fetch row of data from Solid query
Descriptio See odbc_fetch_row()
solid_fieldname solid_fieldname -- get name of column from Solid query
Description See odbc_field_name().
solid_fieldnum solid_fieldnum -- get index of column from Solid query
Description See odbc_field_num().
solid_freeresult solid_freeresult -- free result memory from Solid query
Description See odbc_free_result().
solid_numfields solid_numfields -- get number of fields in Solid result
Description See odbc_num_fields().
solid_numrows solid_numrows -- get number of rows in Solid result
Description See odbc_num_rows().
solid_result solid_result -- get data from Solid results
Description See odbc_result().
XXXVI. SNMP Functions Table of Contents snmpget snmpwalk In order to use the SNMP functions on Unix you need to install the ucd-snmp package. There is a link to the current version in the PHP FAQ. On Windows these functions are only available on NT and not on Win95/98.
snmpget snmpget -- Fetch an SNMP object
Description int snmpget(string hostname, string community, string object_id);
Returns SNMP object value on success and false on error.
The snmpget() function is used to read the value of an SNMP object specified by the object_id. SNMP agent is specified by the hostname and the read community is specified by the community parameter.
snmpget("127.0.0.1", "public", "system.SysContact.0")
snmpwalk snmpwalk -- Fetch all the SNMP objects from an agent
Description array snmpwalk(string hostname, string community, string object_id);
Returns an array of SNMP object values starting from the object_id as root and false on error.
snmpwalk() function is used to read all the values from an SNMP agent specified by the hostname. Community specifies the read community for that agent. A null object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array. If object_id is specified, all the SNMP objects below that object_id are returned.
$a = snmpwalk("127.0.0.1", "public", "");
Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop
for($i=0; $i<count($a); $i++) { echo $a[$i]; }
XXXVII. String functions Table of Contents AddSlashes Chop Chr chunk_split convert_cyr_string crypt echo explode flush get_meta_tags htmlspecialchars htmlentities implode join ltrim md5 nl2br Ord parse_str print printf quoted_printable_decode QuoteMeta rawurldecode rawurlencode setlocale soundex sprintf strchr strcmp strcspn StripSlashes strlen strrpos strpos strrchr strrev strspn strstr strtok strtolower strtoupper str_replace strtr substr trim ucfirst ucwords These functions all manipulate strings in various ways. Some more specialized sections can be found in the regular expression and URL handling sections.
AddSlashes AddSlashes -- quote string with slashes
Description string addslashes(string str);
Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the null byte).
See also stripslashes(), htmlspecialchars() and quotemeta().
Chop Chop -- remove trailing whitespace
Description string chop(string str);
Returns the argument string without trailing whitespace.
Example 1. chop() example
$trimmed = Chop($line);
See also trim().
Chr Chr -- return a specific character
Description string chr(int ascii);
Returns a one-character string containing the character specified by ascii.
Example 1. chr() example
$str .= chr(27); /* add an escape character at the end of $str */
/* Often this is more useful */ $str = sprintf("The string ends in escape: %c", 27);
This function complements ord(). See also sprintf() with a format string of %c.
chunk_split chunk_split -- Split a string into smaller chunks
Description string chunk_split(string string, int [chunklen] , string [end] );
Can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode output to match RFC 2045 behaviour. It inserts every chunklen (defaults to 76) chars the string end (defaults to "\r\n"). It returns the new string leaving the original string untouched.
Example 1. chr_replace() example
# format $data using RFC 2045 semantics
$new_string = chunk_split(base64_encode($data));
This function is significantly faster than ereg_replace().
convert_cyr_string convert_cyr_string -- Convert from one Cyrillic character set to another
Description string convert_cyr_string(string str, string from, string to);
This function converts the given string from one Cyrillic character set to another. The from and to arguments are single characters that represent the source and target Cyrillic character sets. The supported types are:
k - koi8-r
w - windows-1251
i - iso8859-5
a - x-cp866
d - x-cp866
m - x-mac-cyrillic
crypt crypt -- DES-encrypt a string
Description string crypt(string str, string [salt]);
crypt() will encrypt a string using the standard Unix DES encryption method. Arguments are a string to be encrypted and an optional two-character salt string to base the encryption on. See the Unix man page for your crypt function for more information.
If the salt argument is not provided, it will be randomly generated by PHP.
Some operating systems support more than one type of encryption. In fact, sometimes the standard DES encryption is replaced by an MD5 based encryption algorithm. The encryption type is triggered by the salt argument. At install time, PHP determines the capabilities of the crypt function and will accept salts for other encryption types. If no salt is provided, PHP will auto-generate a standard 2-character DES salt by default unless the default encryption type on the system is MD5 in which case a random MD5-compatible salt is generated.
The standard DES encryption crypt() contains the salt as the first two characters of the output.
There is no decrypt function, since crypt() uses a one-way algorithm.
echo echo -- output one or more strings
Description echo(string arg1, string [argn]...);
Outputs all parameters.
echo() is not actually a function (it is a language construct) so you are not required to use parantheses with it.
Example 1. echo example
echo "Hello World";
See also: print() printf() flush()
explode explode -- split a string by string
Description array explode(string separator, string string);
Returns an array of strings containing the elements separated by separator.
Example 1. explode() example
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza);
See also split() and implode().
flush flush -- flush the output buffer
Description void flush(void);
Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc.) This effectively tries to push all the output so far to the user's browser.
get_meta_tags get_meta_tags -- Extracts all meta tag content attributes from a file and returns an array
Description array get_meta_tags(string filename, int [use_include_path]);
Opens filename and parses it line by line for <meta> tags of the form
Example 1. Meta Tags Example
<meta name="author" content="name"> <meta name="tags" content="php3 documentation"> </head> <!-- parsing stops here -->
(pay attention to line endings - PHP3 uses a native function to parse the input, so a Mac file won't work on Unix).
The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '_', the rest is converted to lower case.
Setting use_include_path to 1 will result in PHP3 trying to open the file along the standard include path.
htmlspecialchars htmlspecialchars -- Convert special characters to HTML entities.
Description string htmlspecialchars(string string);
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made.
This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application.
At present, the translations that are done are:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"'
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
Note that this functions does not translate anything beyond what is listed above. For full entity translation, see htmlentities().
See also htmlentities() and nl2br().
htmlentities htmlentities -- Convert all applicable characters to HTML entities.
Description string htmlentities(string string);
This function is identical to htmlspecialchars() in all ways, except that all characters which have HTML entity equivalents are translated into these entities.
At present, the ISO-8859-1 character set is used.
See also htmlspecialchars() and nl2br().
implode implode -- join array elements with a string
Description string implode(array pieces, string glue);
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
Example 1. implode() example
$colon_separated = implode($array, ":");
See also explode(), join(), and split().
join join -- join array elements with a string
Description string join(array pieces, string glue);
join() is an alias to implode(), and is identical in every way.
ltrim ltrim -- Strip whitespace from the beginning of a string.
Description string ltrim(string str);
This function strips whitespace from the start of a string and returns the stripped string.
See also chop() and trim().
md5 md5 -- calculate the md5 hash of a string
Description string md5(string str);
Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm.
nl2br nl2br -- Converts newlines to HTML line breaks.
Description string nl2br(string string);
Returns string with '<BR>' inserted before all newlines.
See also htmlspecialchars() and htmlentities().
Ord Ord -- return ASCII value of character
Description int ord(string string);
Returns the ASCII value of the first character of string. This function complements chr().
Example 1. ord() example
if (ord($str) == 10) { echo("The first character of \$str is a line feed.\n"); }
See also chr().
parse_str parse_str -- parses the string into variables
Description void parse_str(string str);
Parses str as if it were the query string passed via an URL and sets variables in the current scope.
Example 1. Using parse_str()
$str = "first=value&second[]=this+works&second[]=another"; parse_str($str); echo $first; /* prints "value" */ echo $second[0]; /* prints "this works" */ echo $second[1]; /* prints "another" */
print print -- output a string
Description print(string arg);
Outputs arg.
See also: echo() printf() flush()
printf printf -- output a formatted string
Description int printf(string format, mixed [args]...);
Produces output according to format, which is described in the documentation for sprintf().
See also: print(), sprintf(), and flush().
quoted_printable_decode quoted_printable_decode -- Convert a quoted-printable string to an 8 bit string
Description string quoted_printable_decode(string str);
This function returns an 8-bit binary string corresponding to the decoded quoted printable string. This function is similar to imap_qprint(), except this one does not require the IMAP module to work.
QuoteMeta QuoteMeta -- quote meta characters
Description int quotemeta(string str);
Returns a version of str with a backslash character (\) before every character that is among these:
. \\ + * ? [ ^ ] ( $ ) See also addslashes(), htmlentities(), htmlspecialchars(), nl2br(), and stripslashes().
rawurldecode rawurldecode -- decode URL-encoded strings
Description string rawurldecode(string str);
Returns a string in which the sequences with percent (%) signs followed by two hex digits have been replaced with literal characters. For example, the string
foo%20bar%40baz decodes into
foo bar@baz See also rawurlencode().
rawurlencode rawurlencode -- URL-encode according to RFC1738
Description string rawurlencode(string str);
Returns a string in which all non-alphanumeric characters except
-_. have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC1738 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URL's from being mangled by transmission media with character conversions (like some email systems). For example, if you want to include a password in an ftp url:
Example 1. rawurlencode() example 1
echo '<A HREF="ftp://user:', rawurlencode ('foo @+%/'), '@ftp.my.com/x.txt">';
Or, if you pass information in a path info component of the url:
Example 2. rawurlencode() example 2
echo '<A HREF="http://x.com/department_list_script/', rawurlencode ('sales and marketing/Miami'), '">';
See also rawurldecode().
setlocale setlocale -- set locale information
Description string setlocale(string category, string locale);
category is a string specifying the category of the functions affected by the locale setting:
LC_ALL for all of the below
LC_COLLATE for string comparison - not currently implemented in PHP
LC_CTYPE for character classification and conversion, for example strtoupper()
LC_MONETARY for localeconv() - not currently implemented in PHP
LC_NUMERIC for decimal separator
LC_TIME for date and time formatting with strftime()
If locale is the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG".
If locale is zero or "0", the locale setting is not affected, only the current setting is returned.
Setlocale returns the new current locale, or false if the locale functionality is not implemented in the plattform, the specified locale does not exist or the category name is invalid. An invalid category name also causes a warning message.
soundex soundex -- calculate the soundex key of a string
Description string soundex(string str);
Calculates the soundex key of str.
Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.
This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.
Example 1. Soundex Examples
soundex("Euler") == soundex("Ellery") == 'E460'; soundex("Gauss") == soundex("Ghosh") == 'G200'; soundex("Knuth") == soundex("Kant") == 'H416'; soundex("Lloyd") == soundex("Ladd") == 'L300'; soundex("Lukasiewicz") == soundex("Lissajous") == 'L222';
sprintf sprintf -- return a formatted string
Description sprintf(string format, mixed [args]...);
Returns a string produced according to the formatting string format.
The format string is composed by zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf()
Each conversion specification consists of these elements, in order:
An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.
An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.
An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than double. (Another function useful for formatting numbers is number_format().)
A type specifier that says what type the argument data should be treated as. Possible types:
% - a literal percent character. No argument is required. b - the argument is treated as an integer, and presented as a binary number. c - the argument is treated as an integer, and presented as the character with that ASCII value. d - the argument is treated as an integer, and presented as a decimal number. f - the argument is treated as a double, and presented as a floating-point number. o - the argument is treated as an integer, and presented as an octal number. s - the argument is treated as and presented as a string. x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).
See also: printf(), number_format()
Examples Example 1. sprintf: zero-padded integers
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day); Example 2. sprintf: formatting currency
$money1 = 68.75; $money2 = 54.35; $money = $money1 + $money2; // echo $money will output "123.1"; $formatted = sprintf ("%01.2f", $money); // echo $formatted will output "123.10"
strchr strchr -- Find the first occurrence of a character.
Description string strchr(string haystack, string needle);
This function is an alias for strstr(), and is identical in every way.
strcmp strcmp -- binary safe string comparison
Description int strcmp(string str1, string str2);
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
Note that this comparison is case sensitive.
See also ereg(), substr(), and strstr().
strcspn strcspn -- find length of initial segment not matching mask
Description int strcspn(string str1, string str2);
Returns the length of the initial segment of str1 which does not contain any of the characters in str2.
See also strspn().
StripSlashes StripSlashes -- un-quote string quoted with addslashes
Description string stripslashes(string str);
Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes are made into a single backslash.
See also addslashes().
strlen strlen -- get string length
Description int strlen(string str);
Returns the length of string.
strrpos strrpos -- Find position of last occurrence of a char in a string.
Description int strrpos(string haystack, char needle);
Returns the numeric position of the last occurrence of needle in the haystack string. Note that the needle in this case can only be a single character. If a string is passed as the needle, then only the first character of that string will be used.
If needle is not found, returns false.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
See also strpos(), strrchr(), substr(), and strstr().
strpos strpos -- Find position of first occurrence of a string.
Description int strpos(string haystack, string needle, int [offset]);
Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos(), this function can take a full string as the needle parameter and the entire string will be used.
If needle is not found, returns false.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the the beginning of haystack.
See also strrpos(), strrchr(), substr(), and strstr().
strrchr strrchr -- Find the last occurrence of a character in a string.
Description string strrchr(string haystack, string needle);
This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.
Returns false if needle is not found.
If needle contains more than one character, the first is used.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
Example 1. strrchr() example
// get last directory in $PATH $dir = substr( strrchr( $PATH, ":" ), 1 );
// get everything after last newline $text = "Line 1\nLine 2\nLine 3"; $last = substr( strrchr( $text, 10 ), 1 );
See also substr() and strstr().
strrev strrev -- Reverse a string.
Description string strrev(string string);
Returns string, reversed.
strspn strspn -- find length of initial segment matching mask
Description int strspn(string str1, string str2);
Returns the length of the initial segment of str1 which consists entirely of characters in str2.
See also strcspn().
strstr strstr -- Find first occurrence of a string.
Description string strstr(string haystack, string needle);
Returns all of haystack from the first occurrence of needle to the end.
If needle is not found, returns false.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
See also strrchr(), substr(), and ereg().
strtok strtok -- tokenize string
Description string strtok(string arg1, string arg2);
strtok() is used to tokenize a string. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.
Example 1. strtok() example
$string = "This is an example string"; $tok = strtok($string," "); while($tok) { echo "Word=$tok<br>"; $tok = strtok(" "); }
Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.
Also be careful that your tokens may be equal to "0". This evaluates to false in conditional expressions.
See also split() and explode().
strtolower strtolower -- Make a string lowercase.
Description string strtolower(string str);
Returns string with all alphabetic characters converted to lowercase.
Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (? will not be converted.
See also strtoupper() and ucfirst().
strtoupper strtoupper -- Make a string uppercase.
Description string strtoupper(string string);
Returns string with all alphabetic characters converted to uppercase.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (? will not be converted.
See also strtolower() and ucfirst().
str_replace str_replace -- Replace all occurrences of needle in haystack with str
Description string str_replace(string needle, string str, string haystack);
This function replaces all occurences of needle in haystack with the given str. If you don't need fancy replacing rules, you should always use this function instead of ereg_replace().
Example 1. str_replace() example
$bodytag = str_replace("%body%", "black", "<body text=%body%>");
This function is binary safe.
See also ereg_replace().
strtr strtr -- Translate certain characters.
Description string strtr(string str, string from, string to);
This function operates on str, translating all occurrences of each character in from to the corresponding character in to and returning the result.
If from and to are different lengths, the extra characters in the longer of the two are ignored.
Example 1. strtr() example
$addr = strtr($addr, "溴?, "aao");
See also ereg_replace().
substr substr -- Return part of a string.
Description string substr(string string, int start, int [length]);
Substr returns the portion of string specified by the start and length parameters.
If start is positive, the returned string will start at the start'th character of string. Examples:
$rest = substr("abcdef", 1); // returns "bcdef" $rest = substr("abcdef", 1, 3); // returns "bcd" If start is negative, the returned string will start at the start'th character from the end of string. Examples:
$rest = substr("abcdef", -1); // returns "f" $rest = substr("abcdef", -2); // returns "ef" $rest = substr("abcdef", -3, 1); // returns "d" If length is given and is positive, the string returned will end length characters from start. If this would result in a string with negative length (because the start is past the end of the string), then the returned string will contain the single character at start.
If length is given and is negative, the string returned will end length characters from the end of string. If this would result in a string with negative length, then the returned string will contain the single character at start. Examples:
$rest = substr("abcdef", -1, -1); // returns "bcde" See also strrchr() and ereg().
trim trim -- Strip whitespace from the beginning and end of a string.
Description string trim(string str);
This function strips whitespace from the start and the end of a string and returns the stripped string.
See also chop() and ltrim().
ucfirst ucfirst -- Make a string's first character uppercase
Description string ucfirst(string str);
Capitalizes the first character of str if that character is alphabetic.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (? will not be converted.
See also strtoupper() and strtolower().
ucwords ucwords -- Uppercase the first character of each word in a string
Description string ucwords(string str);
Capitalizes the first character of each word in str if that character is alphabetic.
See also strtoupper(), strtolower() and ucfirst().
XXXVIII. URL functions Table of Contents parse_url urldecode urlencode base64_encode base64_decode parse_url parse_url -- parse a URL and return its components
Description array parse_url(string url);
This function returns an associative array returning any of the various components of the URL that are present. This includes the "scheme", "host", "port", "user", "pass", "path", "query", and "fragment".
urldecode urldecode -- decodes URL-encoded string
Description string urldecode(string str);
Decodes any %## encoding in the given string. The decoded string is returned.
Example 1. urldecode() example
$a = split ('&', $querystring); $i = 0; while ($i < count ($a)) { $b = split ('=', $a [$i]); echo 'Value for parameter ', htmlspecialchars (urldecode ($b [0])), ' is ', htmlspecialchars (urldecode ($b [1])), "<BR>"; $i++; }
See also urlencode()
urlencode urlencode -- URL-encodes string
Description string urlencode(string str);
Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the RFC1738 encoding (see rawurlencode() ) in that for historical reasons, spaces are encoded as plus (+ ) signs. This function is convenient when encoding a string to be used in a query part of an URL, as a convinient way to pass variables to the next page:
Example 1. urlencode() example
echo '<A HREF="mycgi?foo=', urlencode ($userinput), '">';
See also urldecode()
base64_encode base64_encode -- encodes data with MIME base64
Description string base64_encode(string data);
base64_encode() returns data encoded with base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
Base64-encoded data takes about 33% more space than the original data.
See also: base64_decode(), RFC-2045 section 6.8.
base64_decode base64_decode -- decodes data encoded with MIME base64
Description string base64_decode(string encoded_data);
base64_decode() decodes encoded_data and returns the original data. The returned data may be binary.
See also: base64_encode(), RFC-2045 section 6.8.
XXXIX. Variable functions Table of Contents gettype intval doubleval empty is_array is_double is_float is_int is_integer is_long is_object is_real is_string isset settype strval unset gettype gettype -- Get the type of a variable.
Description string gettype(mixed var);
Returns the type of the PHP variable var.
Possibles values for the returned string are:
"integer"
"double"
"string"
"array"
"object"
"unknown type"
See also settype().
intval intval -- Get integer value of a variable.
Description int intval(mixed var, int [base]);
Returns the integer value of var, using the specified base for the conversion (the default is base 10).
var may be any scalar type. You cannot use intval() on arrays or objects.
See also doubleval(), strval(), settype() and Type juggling.
doubleval doubleval -- Get double value of a variable.
Description double doubleval(mixed var);
Returns the double (floating point) value of var.
var may be any scalar type. You cannot use doubleval() on arrays or objects.
See also intval(), strval(), settype() and Type juggling.
empty empty -- determine whether a variable is set
Description int empty(mixed var);
Returns false if var exists and has a non-empty or non-zero value; true otherwise.
See also isset() and unset().
is_array is_array -- Finds whether a variable is an array.
Description int is_array(mixed var);
Returns true if var is an array, false otherwise.
See also is_double(), is_float(), is_int(), is_integer(), is_real(), is_string(), is_long(), and is_object().
is_double is_double -- Finds whether a variable is a double.
Description int is_double(mixed var);
Returns true if var is a double, false otherwise.
See also is_array(), is_float(), is_int(), is_integer(), is_real(), is_string(), is_long(), and is_object().
is_float is_float -- Finds whether a variable is a float.
Description int is_float(mixed var);
This function is an alias for is_double().
See also is_double(), is_real(), is_int(), is_integer(), is_string(), is_object(), is_array(), and is_long().
is_int is_int -- Find whether a variable is an integer.
Description int is_int(mixed var);
This function is an alias for is_long().
See also is_double(), is_float(), is_integer(), is_string(), is_real(), is_object(), is_array(), and is_long().
is_integer is_integer -- Find whether a variable is an integer.
Description int is_integer(mixed var);
This function is an alias for is_long().
See also is_double(), is_float(), is_int(), is_string(), is_real(), is_object(), is_array(), and is_long().
is_long is_long -- Finds whether a variable is an integer.
Description int is_long(mixed var);
Returns true if var is an integer (long), false otherwise.
See also is_double(), is_float(), is_int(), is_real(), is_string(), is_object(), is_array(), and is_integer().
is_object is_object -- Finds whether a variable is an object.
Description int is_object(mixed var);
Returns true if var is an object, false otherwise.
See also is_long(), is_int(), is_integer(), is_float(), is_double(), is_real(), is_string(), and is_array().
is_real is_real -- Finds whether a variable is a real.
Description int is_real(mixed var);
This function is an alias for is_double().
See also is_long(), is_int(), is_integer(), is_float(), is_double(), is_object(), is_string(), and is_array().
is_string is_string -- Finds whether a variable is a string.
Description int is_string(mixed var);
Returns true if var is a string, false otherwise.
See also is_long(), is_int(), is_integer(), is_float(), is_double(), is_real(), is_object(), and is_array().
isset isset -- determine whether a variable is set
Description int isset(mixed var);
Returns true if var exists; false otherwise.
If a variable has been unset with unset(), it will no longer be isset().
$a = "test"; echo isset($a); // true unset($a); echo isset($a); // false See also empty() and unset().
settype settype -- Set the type of a variable.
Description int settype(string var, string type);
Set the type of variable var to type.
Possibles values of type are:
"integer"
"double"
"string"
"array"
"object"
Returns true if successful; otherwise returns false.
See also gettype().
strval strval -- Get string value of a variable.
Description string strval(mixed var);
Returns the string value of var.
var may be any scalar type. You cannot use strval() on arrays or objects.
See also doubleval(), intval(), settype() and Type juggling.
unset unset -- Unset a given variable
Description int unset(mixed var);
unset() destroys the specified variable and returns true.
Example 1. unset() example
unset( $foo ); unset( $bar['quux'] );
See also isset() and empty().
XL. Vmailmgr Functions Table of Contents vm_adduser vm_addalias vm_passwd vm_delalias vm_deluser These functions require QMAIL (www.qmail.org) and the vmailmgr package by Bruce Guenter http://www.qcc.sk.ca/~bguenter/distrib/vmailmgr/
For all functions, the following two variables are defined as: string vdomain the domain name of your virtual domain (vdomain.com) string basepwd the password of the 'real' user that holds the virtual users
Only up to 8 characters are recognized in passwords for virtual users
Return status for all functions matches response in response.h
O ok 1 bad 2 error 3 error connecting
Known problems: vm_deluser() does not delete the user directory as it should. vm_addalias() currently does not work correctly.
<?php dl("php3_vmailmgr.so"); //load the shared library $vdomain="vdomain.com"; $basepwd="password"; ?>
vm_adduser vm_adduser -- Add a new virtual user with a password
Description int vm_adduser(string vdomain, string basepwd, string newusername, string newuserpassword);
Add a new virtual user with a password. newusername is the email login name and newuserpassword the password for this user.
vm_addalias vm_addalias -- Add an alias to a virtual user
Description int vm_addalias(string vdomain, string basepwd, string username, string alias);
Add an alias to a virtual user. username is the email login name and alias is an alias for this vuser.
vm_passwd vm_passwd -- Changes a virtual users password
Description int vm_passwd(string vdomain, string username, string password, string newpassword);
Changes a virtual users password. username is the email login name, password the old password for the vuser, and newpassword the new password.
vm_delalias vm_delalias -- Removes an alias
Description int vm_delalias(string vdomain, string basepwd, string alias);
Removes an alias.
vm_deluser vm_deluser -- Removes a virtual user
Description int vm_deluser(string vdomain, string username);
Removes a virtual user..
XLI. Gz-file Functions Table of Contents gzclose gzeof gzfile gzgetc gzgets gzgetss gzopen gzpassthru gzputs gzread gzrewind gzseek gztell readgzfile gzwrite This module uses the functions of zlib >= 1.0.9 (http://www.cdrom.com/pub/infozip/zlib/) by Jean-loup Gailly and Mark Adler to transparently read and write gzip (.gz) compressed files.
gzclose gzclose -- close an open gz-file pointer
Description int gzclose(int zp);
The gz-file pointed to by zp is closed.
Returns true on success and false on failure.
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
gzeof gzeof -- test for end-of-file on a gz-file pointer
Description int gzeof(int zp);
Returns true if the gz-file pointer is at EOF or an error occurs; otherwise returns false.
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
gzfile gzfile -- read entire gz-file into an array
Description array gzfile(string filename);
Identical to readgzfile(), except that gzfile() returns the file in an array.
See also readgzfile(), and gzopen().
gzgetc gzgetc -- get character from gz-file pointer
Description string gzgetc(int zp);
Returns a string containing a single (uncompressed) character read from the file pointed to by zp. Returns FALSE on EOF (as does gzeof()).
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
See also gzopen(), and gzgets().
gzgets gzgets -- get line from file pointer
Description string gzgets(int zp, int length);
Returns a (uncompressed) string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).
If an error occurs, returns false.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
See also gzopen(), and gzgetc().
gzgetss gzgetss -- get line from gz-file pointer and strip HTML tags
Description string gzgetss(int zp, int length);
Identical to gzgets(), except that gzgetss attempts to strip any HTML and PHP tags from the text it reads.
See also gzgets(), and gzopen().
gzopen gzopen -- open gz-file
Description int gzopen(string filename, string mode);
Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen() ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman only compression as in "wb1h". (See the description of deflateInit2 in zlib.h for more information about the strategy parameter.)
Gzopen can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.
Gzopen returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.
If the open fails, the function returns false.
Example 1. gzopen() example
$fp = gzopen("/tmp/file.gz", "r");
See also gzclose().
gzpassthru gzpassthru -- output all remaining data on a gz-file pointer
Description int gzpassthru(int zp);
Reads to EOF on the given gz-file pointer and writes the (uncompressed) results to standard output.
If an error occurs, returns false.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
The gz-file is closed when gzpassthru() is done reading it (leaving zp useless).
gzputs gzputs -- write to a gz-file pointer
Description int gzputs(int zp, string str, int [length]);
gzputs() is an alias to gzwrite(), and is identical in every way.
gzread gzread -- Binary-safe gz-file read
Description string gzread(int zp, int length);
gzread() reads up to length bytes from the gz-file pointer referenced by zp. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.
// get contents of a gz-file into a string $filename = "/usr/local/something.txt.gz"; $zd = gzopen( $filename, "r" ); $contents = gzread( $zd, 10000 ); gzclose( $zd );
See also gzwrite(), gzopen(), gzgets(), gzgetss(), gzfile(), and gzpassthru().
gzrewind gzrewind -- rewind the position of a gz-file pointer
Description int gzrewind(int zp);
Sets the file position indicator for zp to the beginning of the file stream.
If an error occurs, returns 0.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
See also gzseek() and gztell().
gzseek gzseek -- seek on a gz-file pointer
Description int gzseek(int zp, int offset);
Sets the file position indicator for the file referenced by zp to offset bytes into the file stream. Equivalent to calling (in C) gzseek( zp, offset, SEEK_SET ).
If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position.
Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.
See also gztell() and gzrewind().
gztell gztell -- tell gz-file pointer read/write position
Description int gztell(int zp);
Returns the position of the file pointer referenced by zp; i.e., its offset into the file stream.
If an error occurs, returns false.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
See also gzopen(), gzseek() and gzrewind().
readgzfile readgzfile -- output a gz-file
Description int readgzfile(string filename);
Reads a file, decompresses it and writes it to standard output.
Readgzfile() can be used to read a file which is not in gzip format; in this case readgzfile() will directly read from the file without decompression.
Returns the number of (uncompressed) bytes read from the file. If an error occurs, false is returned and unless the function was called as @readgzfile, an error message is printed.
The file filename will be opened from the filesystem and its contents written to standard output.
See also gzpassthru(), gzfile(), and gzopen().
gzwrite gzwrite -- Binary-safe gz-file write
Description int gzwrite(int zp, string string, int [length]);
gzwrite() writes the contents of string to the gz-file stream pointed to by zp. If the length argument is given, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.
Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.
See also gzread(), gzopen(), and gzputs().
XLII. XML Parser Functions Table of Contents xml_parser_create xml_set_element_handler xml_set_character_data_handler xml_set_processing_instruction_handler xml_set_default_handler xml_set_unparsed_entity_decl_handler xml_set_notation_decl_handler xml_set_external_entity_ref_handler xml_parse xml_get_error_code xml_error_string xml_get_current_line_number xml_get_current_column_number xml_get_current_byte_index xml_parser_free xml_parser_set_option xml_parser_get_option utf8_decode utf8_encode
--------------------------------------------------------------------------------
Introduction
--------------------------------------------------------------------------------
About XML XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C). Information about XML and related technologies can be found at http://www.w3.org/XML/.
--------------------------------------------------------------------------------
Installation This extension uses expat, which can be found at http://www.jclark.com/xml/. The Makefile that comes with expat does not build a library by default, you can use this make rule for that:
libexpat.a: $(OBJS) ar -rc $@ $(OBJS) ranlib $@ A source RPM package of expat can be found at http://www.guardian.no/~ssb/phpxml.html.
On UNIX, run configure with the --with-xml option. The expat library should be installed somewhere your compiler can find it. You may need to set CPPFLAGS and LDFLAGS in your environment before running configure if you have installed expat somewhere exotic.
Build PHP. Tada! That should be it.
--------------------------------------------------------------------------------
About This Extension This PHP extension implements support for James Clark's expat in PHP. This toolkit lets you parse, but not validate, XML documents. It supports three source character encodings also provided by PHP: US-ASCII, ISO-8859-1 and UTF-8. UTF-16 is not supported.
This extension lets you create XML parsers and then define handlers for different XML events. Each XML parser also has a few parameters you can adjust.
The XML event handlers defined are:
Table 1. Supported XML handlers
PHP function to set handler Event description xml_set_element_handler() Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags. xml_set_character_data_handler() Character data is roughly all the non-markup contents of XML documents, including whitespace between tags. Note that the XML parser does not add or remove any whitespace, it is up to the application (you) to decide whether whitespace is significant. xml_set_processing_instruction_handler() PHP programmers should be familiar with processing instructions (PIs) already. <?php ?> is a processing instruction, where php is called the "PI target". The handling of these are application-specific, except that all PI targets starting with "XML" are reserved. xml_set_default_handler() What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler. xml_set_unparsed_entity_decl_handler() This handler will be called for declaration of an unparsed (NDATA) entity. xml_set_notation_decl_handler() This handler is called for declaration of a notation. xml_set_external_entity_ref_handler() This handler is called when the XML parser finds a reference to an external parsed general entity. This can be a reference to a file or URL, for example. See the external entity example for a demonstration.
--------------------------------------------------------------------------------
Case Folding The element handler functions may get their element names case-folded. Case-folding is defined by the XML standard as "a process applied to a sequence of characters, in which those identified as non-uppercase are replaced by their uppercase equivalents". In other words, when it comes to XML, case-folding simply means uppercasing.
By default, all the element names that are passed to the handler functions are case-folded. This behaviour can be queried and controlled per XML parser with the xml_parser_get_option() and xml_parser_set_option() functions, respectively.
--------------------------------------------------------------------------------
Error Codes The following constants are defined for XML error codes (as returned by xml_parse()):
XML_ERROR_NONE XML_ERROR_NO_MEMORY XML_ERROR_SYNTAX XML_ERROR_NO_ELEMENTS XML_ERROR_INVALID_TOKEN XML_ERROR_UNCLOSED_TOKEN XML_ERROR_PARTIAL_CHAR XML_ERROR_TAG_MISMATCH XML_ERROR_DUPLICATE_ATTRIBUTE XML_ERROR_JUNK_AFTER_DOC_ELEMENT XML_ERROR_PARAM_ENTITY_REF XML_ERROR_UNDEFINED_ENTITY XML_ERROR_RECURSIVE_ENTITY_REF XML_ERROR_ASYNC_ENTITY XML_ERROR_BAD_CHAR_REF XML_ERROR_BINARY_ENTITY_REF XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF XML_ERROR_MISPLACED_XML_PI XML_ERROR_UNKNOWN_ENCODING XML_ERROR_INCORRECT_ENCODING XML_ERROR_UNCLOSED_CDATA_SECTION XML_ERROR_EXTERNAL_ENTITY_HANDLING
--------------------------------------------------------------------------------
Character Encoding PHP's XML extension supports the Unicode character set through different character encodings. There are two types of character encodings, source encoding and target encoding. PHP's internal representation of the document is always encoded with UTF-8.
Source encoding is done when an XML document is parsed. Upon creating an XML parser, a source encoding can be specified (this encoding can not be changed later in the XML parser's lifetime). The supported source encodings are ISO-8859-1, US-ASCII and UTF-8. The former two are single-byte encodings, which means that each character is represented by a single byte. UTF-8 can encode characters composed by a variable number of bits (up to 21) in one to four bytes. The default source encoding used by PHP is ISO-8859-1.
Target encoding is done when PHP passes data to XML handler functions. When an XML parser is created, the target encoding is set to the same as the source encoding, but this may be changed at any point. The target encoding will affect character data as well as tag names and processing instruction targets.
If the XML parser encounters characters outside the range that its source encoding is capable of representing, it will return an error.
If PHP encounters characters in the parsed XML document that can not be represented in the chosen target encoding, the problem characters will be "demoted". Currently, this means that such characters are replaced by a question mark.
--------------------------------------------------------------------------------
Some Examples Here are some example PHP scripts parsing XML documents.
--------------------------------------------------------------------------------
XML Element Structure Example This first example displays the stucture of the start elements in a document with indentation.
Example 1. Show XML Element Structure
$file = "data.xml"; $depth = array();
function startElement($parser, $name, $attrs) { global $depth; for ($i = 0; $i < $depth[$parser]; $i++) { print " "; } print "$name\n"; $depth[$parser]++; }
function endElement($parser, $name, $attrs) { global $depth; $depth[$parser]--; }
$xml_parser = xml_parser_create(); xml_set_element_handler($xml_parser, "startElement", "endElement"); if (!($fp = fopen($file, "r"))) { die("could not open XML input"); } while ($data = fread($fp, 4096)) { if (!xml_parse($xml_parser, $data, feof($fp))) { die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser))); } } xml_parser_free($xml_parser);
--------------------------------------------------------------------------------
XML Tag Mapping Example Example 2. Map XML to HTML
This example maps tags in an XML document directly to HTML tags. Elements not found in the "map array" are ignored. Of course, this example will only work with a specific XML document type.
$file = "data.xml"; $map_array = array( "BOLD" => "B", "EMPHASIS" => "I", "LITERAL" => "TT" );
function startElement($parser, $name, $attrs) { global $map_array; if ($htmltag = $map_array[$name]) { print "<$htmltag>"; } }
function endElement($parser, $name, $attrs) { global $map_array; if ($htmltag = $map_array[$name]) { print "</$htmltag>"; } }
function characterData($parser, $data) { print $data; }
$xml_parser = xml_parser_create(); // use case-folding so we are sure to find the tag in $map_array xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true); xml_set_element_handler($xml_parser, "startElement", "endElement"); xml_set_character_data_handler($xml_parser, "characterData"); if (!($fp = fopen($file, "r"))) { die("could not open XML input"); } while ($data = fread($fp, 4096)) { if (!xml_parse($xml_parser, $data, feof($fp))) { die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser))); } } xml_parser_free($xml_parser);
--------------------------------------------------------------------------------
XML External Entity Example This example highlights XML code. It illustrates how to use an external entity reference handler to include and parse other documents, as well as how PIs can be processed, and a way of determining "trust" for PIs containing code.
XML documents that can be used for this example are found below the example (xmltest.xml and xmltest2.xml.)
Example 3. External Entity Example
$file = "xmltest.xml";
function trustedFile($file) { // only trust local files owned by ourselves if (!eregi("^([a-z]+)://", $file) && fileowner($file) == getmyuid()) { return true; } return false; }
function startElement($parser, $name, $attribs) { print "<<font color=\"#0000cc\">$name</font>"; if (sizeof($attribs)) { while (list($k, $v) = each($attribs)) { print " <font color=\"#009900\">$k</font>=\"<font color=\"#990000\">$v</font>\""; } } print ">"; }
function endElement($parser, $name) { print "</<font color=\"#0000cc\">$name</font>>"; }
function characterData($parser, $data) { print "<b>$data</b>"; }
function PIHandler($parser, $target, $data) { switch (strtolower($target)) { case "php": global $parser_file; // If the parsed document is "trusted", we say it is safe // to execute PHP code inside it. If not, display the code // instead. if (trustedFile($parser_file[$parser])) { eval($data); } else { printf("Untrusted PHP code: <i>%s</i>", htmlspecialchars($data)); } break; } }
function defaultHandler($parser, $data) { if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") { printf('<font color="#aa00aa">%s</font>', htmlspecialchars($data)); } else { printf('<font size="-1">%s</font>', htmlspecialchars($data)); } }
function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId, $publicId) { if ($systemId) { if (!list($parser, $fp) = new_xml_parser($systemId)) { printf("Could not open entity %s at %s\n", $openEntityNames, $systemId); return false; } while ($data = fread($fp, 4096)) { if (!xml_parse($parser, $data, feof($fp))) { printf("XML error: %s at line %d while parsing entity %s\n", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser), $openEntityNames); xml_parser_free($parser); return false; } } xml_parser_free($parser); return true; } return false; }
function new_xml_parser($file) { global $parser_file;
$xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1); xml_set_element_handler($xml_parser, "startElement", "endElement"); xml_set_character_data_handler($xml_parser, "characterData"); xml_set_processing_instruction_handler($xml_parser, "PIHandler"); xml_set_default_handler($xml_parser, "defaultHandler"); xml_set_external_entity_ref_handler($xml_parser, "externalEntityRefHandler"); if (!($fp = @fopen($file, "r"))) { return false; } if (!is_array($parser_file)) { settype($parser_file, "array"); } $parser_file[$xml_parser] = $file; return array($xml_parser, $fp); }
if (!(list($xml_parser, $fp) = new_xml_parser($file))) { die("could not open XML input"); }
print "<pre>"; while ($data = fread($fp, 4096)) { if (!xml_parse($xml_parser, $data, feof($fp))) { die(sprintf("XML error: %s at line %d\n", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser))); } } print "</pre>"; print "parse complete\n"; xml_parser_free($xml_parser);
?> Example 4. xmltest.xml
<?xml version='1.0'?> <!DOCTYPE chapter SYSTEM "/just/a/test.dtd" [ <!ENTITY plainEntity "FOO entity"> <!ENTITY systemEntity SYSTEM "xmltest2.xml"> ]> <chapter> <TITLE>Title &plainEntity;</TITLE> <para> <informaltable> <tgroup cols="3"> <tbody> <row><entry>a1</entry><entry morerows="1">b1</entry><entry>c1</entry></row> <row><entry>a2</entry><entry>c2</entry></row> <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row> </tbody> </tgroup> </informaltable> </para> &systemEntity; <sect1 id="about"> <title>About this Document</title> <para> <!-- this is a comment --> <?php print 'Hi! This is PHP version '.phpversion(); ?> </para> </sect1> </chapter>
This file is included from xmltest.xml:
Example 5. xmltest2.xml
<?xml version="1.0"?> <!DOCTYPE foo [ <!ENTITY testEnt "test entity"> ]> <foo> <element attrib="value"/> &testEnt; <?php print "This is some more PHP code being executed."; ?> </foo>
xml_parser_create xml_parser_create -- create an XML parser
Description int xml_parser_create(string [encoding]);
encoding (optional)
Which character encoding the parser should use. The following character encodings are supported:
ISO-8859-1 (default) US-ASCII UTF-8
This function creates an XML parser and returns a handle for use by other XML functions. Returns false on failure.
xml_set_element_handler xml_set_element_handler -- set up start and end element handlers
Description int xml_set_element_handler(int parser, string startElementHandler, string endElementHandler);
Sets the element handler functions for the XML parser parser. startElementHandler and endElementHandler are strings containing the names of functions that must exist when xml_parse() is called for parser.
The function named by startElementHandler must accept three parameters:
startElementHandler(int parser, string name, string attribs);
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
name
The second parameter, name, contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.
attribs
The third parameter, attribs, contains an associative array with the element's attributes (if any). The keys of this array are the attribute names, the values are the attribute values. Attribute names are case-folded on the same criteria as element names. Attribute values are not case-folded.
The original order of the attributes can be retrieved by walking through attribs the normal way, using each(). The first key in the array was the first attribute, and so on.
The function named by endElementHandler must accept two parameters:
endElementHandler(int parser, string name);
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
name
The second parameter, name, contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handlers are set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_character_data_handler xml_set_character_data_handler -- set up character data handler
Description int xml_set_character_data_handler(int parser, string handler);
Sets the character data handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept two parameters:
handler(int parser, string data);
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
data
The second parameter, data, contains the character data as a string.
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_processing_instruction_handler xml_set_processing_instruction_handler -- set up processing instruction (PI) handler
Description int xml_set_processing_instruction_handler(int parser, string handler);
Sets the processing instruction (PI) handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
A processing instruction has the following format:
<?target data?> You can put PHP code into such a tag, but be aware of one limitation: in an XML PI, the PI end tag (?>) can not be quoted, so this character sequence should not appear in the PHP code you embed with PIs in XML documents. If it does, the rest of the PHP code, as well as the "real" PI end tag, will be treated as character data.
The function named by handler must accept three parameters:
handler(int parser, string target, string data);
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
target
The second parameter, target, contains the PI target.
data
The third parameter, data, contains the PI data.
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_default_handler xml_set_default_handler -- set up default handler
Description int xml_set_default_handler(int parser, string handler);
Sets the default handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept two parameters:
handler(int parser, string data);
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
data
The second parameter, data, contains the character data. This may be the XML declaration, document type declaration, entities or other data for which no other handler exists.
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_unparsed_entity_decl_handler xml_set_unparsed_entity_decl_handler -- set up unparsed entity declaration handler
Description int xml_set_unparsed_entity_decl_handler(int parser, string handler);
Sets the unparsed entity declaration handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
This handler will be called if the XML parser encounters an external entity declaration with an NDATA declaration, like the following:
<!ENTITY name {publicId | systemId} NDATA notationName> See section 4.2.2 of the XML 1.0 spec for the definition of notation declared external entities.
The function named by handler must accept six parameters:
handler(int parser, string entityName, string base, string systemId, string publicId, string notationName);
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
entityName
The name of the entity that is about to be defined.
base
This is the base for resolving the system identifier (systemId) of the external entity. Currently this parameter will always be set to an empty string.
systemId
System identifier for the external entity.
publicId
Public identifier for the external entity.
notationName
Name of the notation of this entity (see xml_set_notation_decl_handler()).
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_notation_decl_handler xml_set_notation_decl_handler -- set up notation declaration handler
Description int xml_set_notation_decl_handler(int parser, string handler);
Sets the notation declaration handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
A notation declaration is part of the document's DTD and has the following format:
<!NOTATION name {systemId | publicId}> See section 4.7 of the XML 1.0 spec for the definition of notation declarations.
The function named by handler must accept five parameters:
handler(int parser, string notationName, string base, string systemId, string publicId);
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
notationName
This is the notation's name, as per the notation format described above.
base
This is the base for resolving the system identifier (systemId) of the notation declaration. Currently this parameter will always be set to an empty string.
systemId
System identifier of the external notation declaration.
publicId
Public identifier of the external notation declaration.
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_external_entity_ref_handler xml_set_external_entity_ref_handler -- set up external entity reference handler
Description int xml_set_external_entity_ref_handler(int parser, string handler);
Sets the notation declaration handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept five parameters, and should return an integer value. If the value returned from the handler is false (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING.
int handler(int parser, string openEntityNames, string base, string systemId, string publicId);
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
openEntityNames
The second parameter, openEntityNames, is a space-separated list of the names of the entities that are open for the parse of this entity (including the name of the referenced entity).
base
This is the base for resolving the system identifier (systemid) of the external entity. Currently this parameter will always be set to an empty string.
systemId
The fourth parameter, systemId, is the system identifier as specified in the entity declaration.
publicId
The fifth parameter, publicId, is the public identifier as specified in the entity declaration, or an empty string if none was specified; the whitespace in the public identifier will have been normalized as required by the XML spec.
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_parse xml_parse -- start parsing an XML document
Description int xml_parse(int parser, string data, int [isFinal]);
parser
A reference to the XML parser to use.
data
Chunk of data to parse. A document may be parsed piece-wise by calling xml_parse() several times with new data, as long as the isFinal parameter is set and true when the last data is parsed.
isFinal (optional)
If set and true, data is the last piece of data sent in this parse.
When the XML document is parsed, the handlers for the configured events are called as many times as necessary, after which this function returns true or false.
True is returned if the parse was successful, false if it was not successful, or if parser does not refer to a valid parser. For unsuccessful parses, error information can be retrieved with xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number() and xml_get_current_byte_index().
xml_get_error_code xml_get_error_code -- get XML parser error code
Description int xml_get_error_code(int parser);
parser
A reference to the XML parser to get error code from.
This function returns false if parser does not refer to a valid parser, or else it returns one of the error codes listed in the error codes section.
xml_error_string xml_error_string -- get XML parser error string
Description string xml_error_string(int code);
code
An error code from xml_get_error_code().
Returns a string with a textual description of the error code code, or false if no description was found.
xml_get_current_line_number xml_get_current_line_number -- get current line number for an XML parser
Description int xml_get_current_line_number(int parser);
parser
A reference to the XML parser to get line number from.
This function returns false if parser does not refer to a valid parser, or else it returns which line the parser is currently at in its data buffer.
xml_get_current_column_number xml_get_current_column_number -- get current column number for an XML parser
Description int xml_get_current_column_number(int parser);
parser
A reference to the XML parser to get column number from.
This function returns false if parser does not refer to a valid parser, or else it returns which column on the current line (as given by xml_get_current_line_number()) the parser is currently at.
xml_get_current_byte_index xml_get_current_byte_index -- get current byte index for an XML parser
Description int xml_get_current_byte_index(int parser);
parser
A reference to the XML parser to get byte index from.
This function returns false if parser does not refer to a valid parser, or else it returns which byte index the parser is currently at in its data buffer (starting at 0).
xml_parser_free xml_parser_free -- free an XML parser
Description string xml_parser_free(int parser);
parser
A reference to the XML parser to free.
This function returns false if parser does not refer to a valid parser, or else it frees the parser and returns true.
xml_parser_set_option xml_parser_set_option -- set options in an XML parser
Description int xml_parser_set_option(int parser, int option, mixed value);
parser
A reference to the XML parser to set an option in.
option
Which option to set. See below.
value
The option's new value.
This function returns false if parser does not refer to a valid parser, or if the option could not be set. Else the option is set and true is returned.
The following options are available:
Table 1. XML parser options
Option constant Data type Description XML_OPTION_CASE_FOLDING integer Controls whether case-folding is enabled for this XML parser. Enabled by default. XML_OPTION_TARGET_ENCODING string Sets which target encoding to use in this XML parser. By default, it is set to the same as the source encoding used by xml_parser_create(). Supported target encodings are ISO-8859-1, US-ASCII and UTF-8.
xml_parser_get_option xml_parser_get_option -- get options from an XML parser
Description mixed xml_parser_get_option(int parser, int option);
parser
A reference to the XML parser to get an option from.
option
Which option to fetch. See xml_parser_set_option() for a list of options.
This function returns false if parser does not refer to a valid parser, or if the option could not be set. Else the option's value is returned.
See xml_parser_set_option() for the list of options.
utf8_decode utf8_decode -- converts a UTF-8 encoded string to ISO-8859-1
Description string utf8_decode(string data);
This function decodes data, assumed to be UTF-8 encoded, to ISO-8859-1.
See utf8_encode() for an explaination of UTF-8 encoding.
utf8_encode utf8_encode -- encodes an ISO-8859-1 string to UTF-8
Description string utf8_encode(string data);
This function encodes the string data to UTF-8, and returns the encoded version. UTF-8 is a standard mechanism used by Unicodefor encoding wide character values into a byte stream. UTF-8 is transparent to plain ASCII characters, is self-synchronized (meaning it is possible for a program to figure out where in the bytestream characters start) and can be used with normal string comparison functions for sorting and such. PHP encodes UTF-8 characters in up to four bytes, like this:
Table 1. UTF-8 encoding
bytes bits representation 1 7 0bbbbbbb 2 11 110bbbbb 10bbbbbb 3 16 1110bbbb 10bbbbbb 10bbbbbb 4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
Each b represents a bit that can be used to store character data.
|